是否可以仅删除所有值为空的关联数组?
数据来源:
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
[email] =>
)
[1] => Array
(
[name] => bar
[phone] =>
[email] => yahoo.com
)
[2] => Array
(
[name] =>
[phone] =>
[email] =>
)
)
期望的输出:
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
[email] =>
)
[1] => Array
(
[name] => bar
[phone] =>
[email] => yahoo.com
)
)
我试过这个,但遗憾的是我会删除所有数组的空值
$_arr = array_filter(array_map('array_filter', $_arr));
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
)
[1] => Array
(
[name] => bar
[email] => yahoo.com
)
)
我怎么能这样做?谢谢
答案 0 :(得分:2)
也许是一种更流畅的方式,但是:
$array = array_filter($array, function($a) { return array_filter($a); });
由于array_filter
使用true
或false
返回过滤;函数中的array_filter
返回一个评估为false
的空数组,或一个评估为true
的非空数组,主array_filter
基于此进行过滤
答案 1 :(得分:0)
<?php
$collection = array(
"0" => array
(
'name' => "foo",
'phone' => "012345",
'email' => ''
),
"1" => array
(
'name' => "bar",
'phone' => '',
'email' => "yahoo.com",
),
"2" => array
(
'name' => '',
'phone' => '',
'email' => ''
)
);
foreach($collection as $key=> $entry){
if(count(array_filter($entry)) == 0){
unset($collection[$key]);
}
}
print_r($collection);