PHP-Smartest多维数组过滤器

时间:2014-04-17 11:51:37

标签: php arrays multidimensional-array

我有一个多维数组,如下所示

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的最佳方式帮助我吗?
提前致谢!!!

2 个答案:

答案 0 :(得分:0)

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>';

答案 1 :(得分:0)

你必须使用递归函数。希望这可以帮到你

<?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;
}
?>