通过无序多维数组解析仅查找字符串

时间:2016-12-14 04:31:03

标签: php arrays multidimensional-array

我有一个未定义深度的多维数组。

$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
          "dimensional" => array(
             "array" => "foo",
             "something" => 42,
             "something2" => [1,2,3]
         )
    )
);

我需要解析它,找到所有的平面文本值并将它们保存在另一个保持路径的数组中。所以我希望最终的数组是这样的:

$array = array(
    "foo" => "bar",
    "multi" => array(
          "dimensional" => array(
             "array" => "foo"
         )
    )
);

目前我正在尝试使用循环功能

$this->printAll($array);

public function printAll($a)
    {
        if (!is_array($a)) {
            echo $a, ' <br>'; // here we can check if it is string and add to the final array
            return;
        }

        foreach($a as $i=>$v) {
            $this->printAll($v);
            echo $i;
        }
    }

有人可以帮我弄清楚如何通过迭代保持索引并将其放在最终数组中。

1 个答案:

答案 0 :(得分:1)

<?php

function printAll($array, &$save)
{
    foreach ($array as $key => $values)
    {
        if ( ! is_numeric($values))
        {
            if (is_array($values))
            {
                printAll($values, $save[$key]);
            }
            else
            {
                $save[$key] = $values;
            }
        }
    }
    if ( ! empty($save)) {
        $save = array_filter($save);
    }
}

$array = array(
    "foo" => "bar",
     42   => 24,
    "multi" => array(
          "dimensional" => array(
             "array" => "foo",
             "something" => 42,
             "something2" => [1,2,3]
         )
    )
);

$save = array();
printAll($array, $save);

print_r($save);

输出:PHP

Array (
     [foo] => bar 
     [multi] => Array ( 
        [dimensional] => Array ( 
              [array] => foo 
)))