Search code examples
phparraysrecursionmultidimensional-arraykey

Copy key to value for all empty non-array elements in a multidimensional array


I have an associative multidimensional array like this:

[
    7 => [49 => null, 41 => null],
    8 => [70 => null, 69 => null],
    105 => null,
    9 => null,
    10 => null
]

Now, I need to work with each key, but I am struggling to access all elements through a foreach() loop -- because there are no values. I have been trying to use array_keys(), but that is not suitable for multidimensional keys.

Is there a way I can assign the keys as the values to have a structure like this?

Array
(
    [7] => Array
        (
            [49] => 49
            [41] => 41
        )

    [8] => Array
        (
            [70] => 70
            [69] => 69
        )

    [105] => 105
    [9] => 9
    [10] => 10
)

This way I could use a foreach() to get the values of each key.


Solution

  • We can use array_walk_recursive in this case. In the callback function of array_walk_recursive if we pass the element reference then inside the callback function we can change the empty value with key.

    array_walk_recursive($arr, function(&$item, $key){
        if(!$item && $key) $item  = $key;
    });
    
    print_r($arr);