PHP:从数组中删除空值,然后将其转换为字符串
PHP: Remove empty values from array, then convert that to a string
我知道如何分别完成这些事情(删除空值,并将数组转换为逗号分隔的字符串)但我无法让它们结合使用,而且还没有能够找到这样做的好方法。我知道我可以使用 print_r 来显示我的过滤器的结果,但这没有帮助,因为我最终需要将我的结果字符串发送到数据库(那是另一天)。感谢您的帮助!
我有:
$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
尝试这种方式,无需将过滤后的内容推送到另一个数组并获得 $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: "If no callback is supplied, all entries of input equal
to FALSE will be removed." This means that elements with values NULL,
0, '0', '', FALSE, array() will be removed from it.
我知道如何分别完成这些事情(删除空值,并将数组转换为逗号分隔的字符串)但我无法让它们结合使用,而且还没有能够找到这样做的好方法。我知道我可以使用 print_r 来显示我的过滤器的结果,但这没有帮助,因为我最终需要将我的结果字符串发送到数据库(那是另一天)。感谢您的帮助!
我有:
$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
尝试这种方式,无需将过滤后的内容推送到另一个数组并获得 $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: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed from it.