Search code examples
phpforeachdimension

Get data from multi dimension array


I'm a newbie learning PHP. Today i have a project and being stuck, it broken my brand :(. Hope anybody can help me solved it.

Example i have a Array with construct :

Array ( 
    [a] => Array ( 
        [__base_val] => A 
        [c] => Array ( 
            [__base_val] => C 
            [e] => E 
            [f] => F 
        ) 
        [d] => D 
    ) 
    [b] => Array ( 
        [__base_val] => B 
        [g] => G 
    ) 
    [h] => H 
)

Now i need get value if each node and print out a tree of value. But if using foreach function, i only can get one or two or any index of dimension if i know before.

How i can write a php code for get value follow index dimensions of array and i don't need to know the number of dimension ?

This is result i want:

class1: value from [__base_val]
class2: value from [__base_val]
child class 2 : value

Solution

  • I'm not sure if this is what you're looking for, but I hope it is.

    <?php
    function print_deep($value, $key) {
        echo "$value: value from $key\n";
    }
    
    // Note: $array being the input array
    array_walk_recursive($array, 'print_deep');