2015-04-22 43 views
-2

我知道如何分别做这些事情(删除空值,并将数组转换为逗号分隔的字符串),但我不能让他们一起工作,还没有找到一个好办法。我知道我可以使用print_r来显示我的过滤器的结果,但这没有什么帮助,因为我最终需要将我的结果字符串发送到数据库(这是另一天)。任何帮助表示赞赏!PHP:从数组中删除空值,然后将其转换为字符串

我:

$array = array('item1', 'item2', '', 'item4'); 
//this should filter out the empty values (index 3) 
$filter = array(array_filter($array)); 
//this should then take that filtered array and convert to a comma-separated string 
$comma_separated = implode(",", $filter); 
echo $comma_separated; 

每次我尝试这是我从输出就是:

Array 
+3

你把你的过滤数组放入另一个数组! 'array(array_filter($ orderArray));'你也应该得到一个错误,这意味着你没有打开错误报告! – Rizier123

+2

另外,$ orderArray不存在。 – Matheno

+0

就像一个FYI,'array_filter'的返回类型是一个数组。根据[文档](http://php.net/manual/en/function.array-filter.php):_“返回已过滤的数组...”_ – War10ck

回答

1

试试这个方法,没必要把你的过滤到另一个阵列&,你以后得到$orderArray

$array = array('item1', 'item2', '', 'item4'); 
$filter=array_filter($array); // see here, i didn't add another array() 
$comma_separated = implode(",", $filter); 
echo $comma_separated; 

编辑:较短的方式做到这一点,礼貌 @MHakvoort

$comma_separated = implode(",", array_filter($array)); 

array_filter:“如果没有回调提供,等于 为FALSE输入的所有条目会删除“。这意味着具有值NULL, 0,'0','',FALSE,array()的元素将从其中移除。

+2

这可以缩短:$ comma_separated = implode(“ ,“,array_filter($ array)); – Matheno

+0

@Mhakvoort,感谢更短的版本 –

相关问题