I am trying to flatten and concatenate some nested arrays in PHP, whatever the dimension of the array, and return a single level array of all the concatenated data.
Given array:
[
'dashboards' => [
'statistics' => [
'tab_names' => [
'spare',
'robot',
]
]
]
];
Desired output:
[
'dashboards_statistics_tab_names_spare',
'dashboards_statistics_tab_names_robot',
];
However, I tried to adapt some code found here, came up with that:
function flattenArray($array, $prefix = '') {
$result = [];
foreach ($array as $key => $value) {
$newKey = $prefix . $key;
if (is_array($value)) {
$result = array_merge($result, flattenArray($value, $newKey . '_'));
} elseif (is_string($value)) {
$result[] = $newKey . '_' . $value;
}
}
return $result;
}
The output is almost OK, but I’m having some unwated characters in the strings:
[
'dashboards_statistics_tab_names_0_spare',
'dashboards_statistics_tab_names_1_robot',
];
How can I get rid of the numeric keys ?
3
Answers
I just made some changes in your code, if the
$key
may be anumeric
when no index is given.I also use
rtrim
to avoid extra _ at the end of the string when it’s the last value of an array.Improving the suggestion of @user3783243 a solution can be this:
The prefix is not updated if the key is numeric (last array level) and also the underscore is not added for values of type string
I think to get rid of the numeric keys, the code for checking for numeric keys should be added to the codebase.
I attached my code snippet: