PHP -使多维数组从数组名到字符串数组

mgdq6dx1  于 2023-01-12  发布在  PHP
关注(0)|答案(1)|浏览(125)

我有这样一个多维数组:

array (
   level1 => array ( level1.1,
                     level1.2)
   level2 => array ( level2.1,
                     level2.2 => array( level2.2.1 => 'foo',
                                        level2.2.2 => 'bar',
                                        level2.2.3 => 'test')
   )
)

因此我需要一个字符串数组

array ("level1/level1.1",
       "level1/level1.2",
       "level2/level2.1",
       "level2/level2.2/level2.2.1",
       "level2/level2.2/level2.2.2",
       "level2/level2.2/level2.2.3")

下面是我尝试的代码

function displayArrayRecursively($array, string $path) : array {

        if($path == "")
            $result_array = array();

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $this->displayArrayRecursively($value, $path . $key . '/');
            } else {
                $result_array[] = $path . $key;            }
        }

        return $result_array;
    }

知道我该怎么做吗,我可以用一个引用数组来填充,但是我想用返回值来解决它。

svdrlsy4

svdrlsy41#

$array = [
       'level1' => [
           'level1.1',
           'level1.2'
       ],
       'level2' => [
           'level2.1',
           'level2.2' => [
               'level2.2.1' => 'foo',
               'level2.2.2' => 'bar',
               'level2.2.3' => 'test'
           ]
       ]
   ];

    function arrayParser(array $array, ?string $path=null) {
       $res = [];
       foreach($array as $key => $value) {
           if(is_array($value)) {
               $res[] = arrayParser($value, ($path ? $path.'/' : $path).$key);
           }
           else {
               $res[] = $path.'/'.(!is_numeric($key) ? $key : $value);
           }
       }

       return flatten($res);
   }

    function flatten(array $array) {
        $return = array();
        array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
        return $return;
    }

    $res = arrayParser($array); // result

相关问题