I've been having a little trouble trying to flatten arrays in a specific way.
Here is a print_r
view of the array I want to flatten:
Array
(
[1] => Array
(
[8] => 1
[9] => 2
[10] => Array
(
[15] => Array
(
[22] => 1
)
[21] => 2
)
[11] => Array
(
[16] => Array
(
[23] => 1
)
)
)
[2] => Array
(
[12] => 1
)
[3] => Array
(
[13] => 1
)
[4] => Array
(
[14] => 1
)
[5] => 5
[6] => 6
[7] => 7
)
What I'm attempting to create is an array which keeps the above indexes, but the value is equal to it's position in the array, much like the original index (starting from zero).
Here is the desired result:
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 1
[9] => 2
[10] => 3
[11] => 4
[12] => 1
[13] => 1
[14] => 1
[15] => 1
[16] => 1
[21] => 2
[22] => 2
[23] => 1
)
Knowingly, 17 to 20 are missing.
My function is as follows:
function array_flatten ($array) {
$result = array ();
$count = 1;
while ($index = current($array)) {
$result[key($array)] = $count;
if (is_array($index)) {
$result = array_merge(array_flatten($index), $result);
}
next($array);
$count++;
}
return $result;
}
The line $result = array_merge(array_flatten($index), $result);
appears to be the problems. It returns:
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
)
However, if I run var_dump(array_flatten($index));
on the same line, it returns all the arrays I wish to merge to the $result
variable.
array
22 => int 1
array
15 => int 1
21 => int 2
array
23 => int 1
array
16 => int 1
array
8 => int 1
9 => int 2
10 => int 3
11 => int 4
array
12 => int 1
array
13 => int 1
array
14 => int 1
It seems that that array_merge
doesn't actually merge these arrays.
Is there something I am doing wrong? Any words of guidance are very much appreciated. Thank you.
Update
Solved!
The function which does the required is as follows:
function array_flatten($array, &$result = array()) {
$count = 1;
foreach($array as $index => $value) {
$result[$index] = $count;
if(is_array($value)) {
array_flatten($value, $result);
}
$count++;
}
return $result;
}