$nestedArray = [
'firstLevel1' => [
'secondLevel1' => [
'thirdLevel1' => 'thirdLevel1 value'
],
'secondLevel2' => 'secondLevel2 value'
],
'firstLevel2' => 'firstLevel2 value'
];
var_export(toPseudoNestedAray($nestedArray));
//array (
// 'firstLevel1[secondLevel1][thirdLevel1]' => 'thirdLevel1 value',
// 'firstLevel1[secondLevel2]' => 'secondLevel2 value',
// 'firstLevel2' => 'firstLevel2 value'
//)
function flattenArray($array, &$resultArray = [], $name = '')
{
foreach($array as $key => $value) {
if (is_array($value)) {
flattenArray($value, $resultArray, $name ? $name."[$key]" : $key);
} else {
$resultArray[$name ? $name."[$key]" : $key] = $value;
}
}
return $resultArray;
}
[
'firstLevel1.secondLevel1.thirdLevel1' => 'thirdLevel1 value',
'firstLevel1.secondLevel2' => 'secondLevel2 value'
]
function toPseudoNestedArray(array $array) {
$result = [];
$resultingKey = '';
($closure = function (array $array) use (&$result, &$resultingKey, &$closure) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$currentKey = $resultingKey;
if ($resultingKey) {
$resultingKey .= '[' . $key . ']';
} else {
$resultingKey .= $key;
}
$closure($value);
$resultingKey = $currentKey;
} else {
$result[$resultingKey ? $resultingKey . '[' . $key . ']' : $key] = $value;
}
}
})($array);
return $result;
}
function createPlainArrayFromNested($arr, $path = []) {
$result = [];
foreach ($arr as $key => $val) {
$path[] = count($path) ? "[$key]" : $key;
$result += (is_array($val) && !empty($val))
? createPlainArrayFromNested($val, $path)
: [ implode('', $path) => $val ];
array_pop($path);
}
return $result;
}