0

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.

1 Answer 1

1
    $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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quiclk response. Code works great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.