Hi i have many children arrays inside array all data exactly comes from api output result is i tried array recursive php but not worked
Array
(
[0] => Array
(
[price] => 100
[weight] => 42
[sub_option] => Array
(
[0] => Array
(
[price] => 25.99
[points] => 32
[sub_option] => Array
(
[0] => Array
(
[price] => 27.99
[weight] => 83
[sub_option] => Array
(
[0] => Array
(
[price] => 14.99
[weight] => 50
[sub_option] => NULL
)
)
)
)
)
[1] => Array
(
[price] => 24.99
[weight] => 25
[sub_option] => NULL
)
)
)
[1] => Array
(
[price] => 100
[weight] => 4233
[sub_option] => NULL
)
)
like this but i want output like this ……
Array
(
[0] => Array
(
[price] => 100
[weight] => 42
)
[1] => Array
(
[price] => 25.99
[points] => 32
)
[2] => Array
(
[price] => 27.99
[weight] => 83
)
[3] => Array
(
[price] => 14.99
[weight] => 50
[sub_option] => NULL
)
[4] => Array
(
[price] => 24.99
[weight] => 25
[sub_option] => NULL
)
[5] => Array
(
[price] => 100
[weight] => 4233
[sub_option] => NULL
)
)
I am using PHP version 7 and i also tried to search many online solutions from stackoverflow but i cant find please help me thanks
I tried this code but not working
$output = [];
$arr1 = [];
$arr2 = [];
foreach($arr as $key=>$value){
$arr1 = [
'price' => $value['price'],
'weight' => $value['weight'],
];
if(isset($value['sub_option']) && is_array($value['sub_option'])){
foreach($value['sub_option'] as $val2){
$arr2 = [
'price' => $val2['price'],
'weight' => $val2['weight'],
];
}
}
$output[] = $arr1+$arr2;
}
print_r($output);
2
Answers
Here is one method of doing this
Let’s assume your array is called
$arr
. Here is the output ofprint_r(format_array($arr));
Here is another method to doing this (with anonymous function)
I will not explain this in detail, because first answer from GrumpyCrouton should be taken/accepted. But when you take some time, may you learn new stuff and how php works from this little code snipped.