<?php
function flatten($array, $prefix = '') {
$return = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$return = array_merge($return, flatten($value, $prefix . $key . '_'));
} else {
$return[$prefix . $key] = $value;
}
}
return $return;
}
// proof that it's working on the simple cases
var_dump(flatten([
1, 2, 3 => [4, 5]
]));
var_dump(flatten([
[1, 2], [3, 4]
])); // use array_values on the result if you don't care about keys
// simple multidimensional array
var_dump(flatten([
'a' => [
'b' => 'value',
]
]));
// proof that it's not overwriting values like all the other solutions
var_dump(flatten([
'a' => [
'b' => 'value',
],
'c' => [
'b' => 'anothervalue',
],
]));
preferences:
30.75 ms | 405 KiB | 5 Q