我有一个多维数组,如下
Array
(
[0] => Array
(
[1] => val01
[2] => val02
[3] =>
)
[1] => Array
(
[1] => val11
[2] => Array
(
[sub1] => 1
[sub2] =>
[sub3] => Array
(
[primarysub1] =>
[primarysub2] => pmy2
)
)
[3] => val3
)
[2] => Array
(
[1] => val21
[2] =>
[3] => val23
)
)
我需要过滤空值,预期输出如下。
Array
(
[0] => Array
(
[1] => val01
[2] => val02
)
[1] => Array
(
[1] => val11
[2] => Array
(
[sub1] => 1
[sub3] => Array
(
[primarysub2] => pmy2
)
)
[3] => val3
)
[2] => Array
(
[1] => val21
[3] => val23
)
)
有人能帮我找到使用PHP的最佳方法吗?
您必须为此使用递归函数。希望这能帮助你
<?php
$rs = unsetValues($arr);
function unsetValues($a)
{
foreach($a as $k=>$v)
{
if(is_array($v))
{
$arr2[$k] = unsetValues($v);
} else {
if($v!="")
$arr2[$k] = $v;
}
}
return $arr2;
}
?>
function filter($input, $callback = null)
{
foreach ($input as &$value)
{
if (is_array($value))
{
$value = filter($value, $callback);
}
}
return array_filter($input, $callback);
}
function remove_empty($val)
{
return !empty($val);
}
$test_arr = array(
0 => array(1 => "val01", 2 => "val02", 3 => ""),
1 => array(1 => "val11", 2 => array("sub1" => 1, "sub2" => "", "sub3" => array("primarysub1" => "", "primarysub2" => "pmy2")), 3 => "val3"),
2 => array(1 => "val21", 2 => "", 3 => "val23")
);
echo '<pre>' . print_r($test_arr, true) . '</pre>';
// filter empty
$result = filter($test_arr, remove_empty);
echo '<pre>' . print_r($result, true) . '</pre>';