我正在使用Laravel 5.3
。
我有multidimensional array
喜欢:
Array
(
[id] => 37141
[last_done_on] => []
[children] => Array
(
[0] => NULL /* This must be removed */
[1] => Array
(
[id] => 37142
[last_done_on] => Array()
[children] => Array()
)
[2] => Array
(
[id] => 37143
[last_done_on] => Array()
[children] => Array
(
[0] => Array
(
[id] => 37144
[last_done_on] => Array()
[children] => Array()
)
[1] => Array
(
[id] => 37145
[last_done_on] => Array()
[children] => Array()
)
)
)
[3] => Array
(
[id] => 37157
[last_done_on] => Array()
[children] => Array
(
[0] => Array
(
[id] => 37158
[last_done_on] => Array()
[children] => Array()
)
[1] => Array
(
[id] => 37159
[last_done_on] => Array()
[children] => Array
(
[0] => NULL /* This must be removed */
)
)
)
)
)
)
我希望remove
elements
NULL
。所以结果应该是:
Array
(
[id] => 37141
[last_done_on] => []
[children] => Array
(
[0] => Array
(
[id] => 37142
[last_done_on] => Array()
[children] => Array()
)
[1] => Array
(
[id] => 37143
[last_done_on] => Array()
[children] => Array
(
[0] => Array
(
[id] => 37144
[last_done_on] => Array()
[children] => Array()
)
[1] => Array
(
[id] => 37145
[last_done_on] => Array()
[children] => Array()
)
)
)
[2] => Array
(
[id] => 37157
[last_done_on] => Array()
[children] => Array
(
[0] => Array
(
[id] => 37158
[last_done_on] => Array()
[children] => Array()
)
[1] => Array
(
[id] => 37159
[last_done_on] => Array()
[children] => Array
(
)
)
)
)
)
)
怎么做?
答案 0 :(得分:5)
如果要删除null
值而不删除空数组,可以执行以下操作:
function array_remove_null($item)
{
if (!is_array($item)) {
return $item;
}
return collect($item)
->reject(function ($item) {
return is_null($item);
})
->flatMap(function ($item, $key) {
return is_numeric($key)
? [array_remove_null($item)]
: [$key => array_remove_null($item)];
})
->toArray();
}
$newArray = array_remove_null($array);
希望这有帮助!
答案 1 :(得分:5)
在收藏中,使用过滤器
some_collection->filter(function($value, $key) {
return $value != null;
});
答案 2 :(得分:2)
试试这个:
function array_filter_recursive($input)
{
foreach ($input as &$value)
{
if (is_array($value))
{
$value = array_filter_recursive($value);
}
}
return array_filter($input, function($var){return !is_null($var);} );
}
答案 3 :(得分:1)
试一试:
$yourArr= array_map('array_filter', $yourArr);
$yourArr= array_filter( $yourArr);