1

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.

0

3 Answers 3

2

Use array_walk_recursive() to assign the key as value to each entry whose value is not an array.

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

3 Comments

The callback receives the key as an argument, but it doesn't receive the array, so how will it know which subarray to assign the value to?
@barmar if we pass the element reference and change the value inside callback function then it will be fine.
@BerozaPaul I see that in your answer. This answer didn't mention that detail, and it's not obvious.
1

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

Comments

1

From PHP7.4, you can enjoy the brevity of "arrow function" syntax. You still need to make the leafnode's value modifiable by reference and manually assign $k's value to $v. The arrow function syntax attempts (by default) to return the value in the expression, but the return value is ignored.

Code: (Demo)

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

array_walk_recursive($array, fn(&$v, $k) => $v = $k);
var_export($array);

Output:

array (
  7 => 
  array (
    49 => 49,
    41 => 41,
  ),
  8 => 
  array (
    70 => 70,
    69 => 69,
  ),
  105 => 105,
  9 => 9,
  10 => 10,
)

Comments

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.