I have a multidimensional array like
$inputArray = array(
array(
array('value31', 'value32'),
array('value33', 'value34'),
'value21'
),
'value11'
);
I need to pop the last item from each item and considered it as the key for rest values. Output array should like,
$outputArray = array(
'value11' => array(
'value21' => array(
array('value31', 'value32'),
array('value33', 'value34'),
)
)
);
I tried this code, but it doesn’t work.
function convertArray(array $inputArray, $old_key = null) {
$outputArray = [];
$isMultiDimensional = count($inputArray) != count($inputArray, COUNT_RECURSIVE);
$array_key = $isMultiDimensional ? array_pop($inputArray) : $old_key;
foreach ($inputArray as $value) {
$itemIsMultiDimensional = count($value) != count($value, COUNT_RECURSIVE);
if (is_array($value) && $itemIsMultiDimensional) {
$outputArray = array_merge($outputArray, convertArray($value, $array_key));
} else {
$outputArray[$array_key][] = $value;
}
}
return $outputArray;
}
2
Answers
In your
foreach
change theif
and check