'array keys as values with multidimensional array
I currently have an array looking like this
Array
(
[7] => Array
(
[49] =>
[41] =>
)
[8] => Array
(
[70] =>
[69] =>
)
[105] =>
[9] =>
[10] =>
)
Now, I need each to work with each key, but I struggle getting those through a foreach() loop, because there is no values. I have been trying to use array_keys, but that disregards multidimensional keys. Is there a way I can assign the keys as the values as well, 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. I don't know if this is the easiest way, but I would love to get some hints into the right direction. Thanks!
Solution 1:[1]
Use array_walk_recursive() to assign the key as value to each entry whose value is not an array.
Solution 2:[2]
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,
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RhinoDevel |
| Solution 2 | mickmackusa |
