array(
array(
'drive'=>array('test1'),
'wheel_drive'=>array('2WD','4WD')
),
array(
0=>array(
'drive'=>array('test21','test31'),
'wheel_drive'=>array('2WD','4WD')
),
1=>array(
'drive'=>array('test32'),
'wheel_drive' => array('4WD')
)
),
array(
'drive' => array('test4'),
'wheel_drive'=> array('2WD','4WD')
)
);
Output:
array(
array('drive'=>array('test1'),'wheel_drive'=>array('2WD','4WD')),
array('drive'=>array('test21','test31'),'wheel_drive'=>array('2WD','4WD')),
array('drive'=> array('test32'),'wheel_drive' => array('4WD')),
array('drive' => array('test4'),'wheel_drive'=> array('2WD','4WD'))
);
How can we get child array out of main array and then merge it into parent array as its node.
function flattenArray($key, $array) {
$result = array();
foreach ($array as $k=> $element) {
if (is_array($element)) {
$result = array_merge($result, flattenArray($k, $element));
} else {
$result[$key][] = $element;
}
}
return $result;
}
$outputArray = array();
foreach ($inputArray as $key=> $item) {
$outputArray[] = flattenArray($key, $item);
}
print_r($outputArray);
I have this array in which I am trying to extract sub-array and merge into main array so that my result would be like this
one array with all child array with save depth.
2
Answers
With a slight modification to your code you can extract the array you want:
See: https://3v4l.org/Ut27X
That being said: The data array doesn’t make sense. I think it would be better to work on the code that generates this data array. Prevent the problem from occurring in the first place.