<?php
$testArray = [
['lev 1' => 'lev 1'],
['lev 2', 'lev 2 - 1', ['lev 2 - 2'], ['Key preserved' => 'lev 2 - 3']],
[['lev 3 - 1', 'lev 3 - 2', 'lev 3 - 3']],
[[[888 => 'lev 4']]]
];
// $element must initially be an array. Anything that is not an array will just return the accumulator.
function flatten($element, $accum = []) {
// If we don't have an array return the accumulator.
if (!is_array($element)) {
return $accum;
}
foreach($element as $key => $e) {
// Check if the elements are an array or not. If not, append the accumulator with a key and value.
if (!is_array($e)) {
// Check that the key does not already exist, if it does we have to simply append to preserve values.
if (array_key_exists($key, $accum)) {
$accum[] = $e;
} else {
$accum[$key] = $e;
}
}
// Only recurse when we have an array.
if (is_array($e)) {
// We pass in the accumulator and any values further down then hierachy.
$vals = flatten($e, $accum);
// We might get an empty array back if there was an array of arrays.
if (!empty($vals)) {
// We don't append our values here, we override the accumulator. The appending happens above when $e is not an
// array.
$accum = $vals;
}
}
}
// Return values of this array and all child arrays.
return $accum;
}
var_dump(flatten($testArray));