I have found numerous examples to convert a multidimensional array to a single dimensional array. I am needing to keep the data in the arrays together, just bring them out of nesting and into the first main array.
Here is the array:
Array
(
[0] => Array
(
[id] => 2
[username] => user2
[downline] => Array
(
[0] => Array
(
[id] => 5
[username] => user5
[downline] => Array
(
[0] => Array
(
[id] => 9
[username] => user9
[downline] => Array
(
[0] => Array
(
[id] => 15
[username] => user15
)
[1] => Array
(
[id] => 16
[username] => user16
)
)
)
[1] => Array
(
[id] => 10
[username] => user10
[downline] => Array
(
[0] => Array
(
[id] => 17
[username] => user17
)
)
)
)
)
)
)
[1] => Array
(
[id] => 3
[username] => user3
[downline] => Array
(
[0] => Array
(
[id] => 6
[username] => user6
[downline] => Array
(
[0] => Array
(
[id] => 11
[username] => user11
[downline] => Array
(
[0] => Array
(
[id] => 18
[username] => user18
)
)
)
)
)
)
)
[2] => Array
(
[id] => 4
[username] => user4
[downline] => Array
(
[0] => Array
(
[id] => 7
[username] => user7
[downline] => Array
(
[0] => Array
(
[id] => 12
[username] => user12
[downline] => Array
(
[0] => Array
(
[id] => 19
[username] => user19
)
)
)
)
)
[1] => Array
(
[id] => 8
[username] => user8
[downline] => Array
(
[0] => Array
(
[id] => 13
[username] => user13
)
[1] => Array
(
[id] => 14
[username] => user14
)
)
)
)
)
)
This is for messaging all their team members. I don't care who they are under, I just need a full running list of all the users, so I can loop through and send them a message in the system.
So here is an example of the final array I am trying to get:
[
[id] => 2
[username] => user2
],
[
[id] => 5
[username] => user5
],
[
[id] => 9
[username] => user9
],
[
[id] => 15
[username] => user15
],
[
[id] => 16
[username] => user16
],
[
[id] => 10
[username] => user10
],
[
[id] => 17
[username] => user17
],
[
[id] => 3
[username] => user3]
],
// ... and so on
Ideally, the array keys could be their user id. This will be going in a dropdown menu where they can choose a member of their team, or they can message all of them. Something like this:
[
1 => 'user1',
2 => 'user2',
9 => 'user9',
]
I have tried variations of array_merge
, array_walk_recursive
.. Everything just flattens it all into one ugly 1 dimensional array..
Something like this, which didn't work:
function flatten(array $arr) {
return array_reduce($arr, function ($c, $a) {
return is_array($a) ? array_merge($c, flatten($a)) : array_merge($c, [$a]);
},
[]);
}