Home > Software design >  PHP - make multidimensional array to array of strings from the arrays names
PHP - make multidimensional array to array of strings from the arrays names

Time:01-10

I have a multidimensional array like this:

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

As a result I want an array of strings like this

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")

Here is the code I tried

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

Any idea how I can achieve this. I could use a reference array to populate, but I want to solve it with return values.

CodePudding user response:

    $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

enter image description here

  • Related