<?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',
],
]));
- Output for 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.13
- array(4) {
[0]=>
int(1)
[1]=>
int(2)
["3_0"]=>
int(4)
["3_1"]=>
int(5)
}
array(4) {
["0_0"]=>
int(1)
["0_1"]=>
int(2)
["1_0"]=>
int(3)
["1_1"]=>
int(4)
}
array(1) {
["a_b"]=>
string(5) "value"
}
array(2) {
["a_b"]=>
string(5) "value"
["c_b"]=>
string(12) "anothervalue"
}
preferences:
70.06 ms | 408 KiB | 5 Q