嗨,我有很多子数组里面数组所有的数据完全来自API输出结果是我尝试数组递归php,但没有工作
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
)
)
像这样,但我希望输出像这样......
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
)
)
我正在使用PHP版本7,我也试图从stackoverflow搜索许多在线解决方案,但我找不到请帮助我,谢谢
我尝试了此代码,但不工作
$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条答案
按热度按时间toiithl61#
下面是一种方法
假设您的数组名为
$arr
,下面是print_r(format_array($arr));
的输出hc2pp10m2#
下面是另一种方法(使用匿名函数)
我不会详细解释这个,因为第一个答案GrumpyCrouton应该采取/接受。但当你花一些时间,希望你能学到新的东西和php如何从这个小代码剪工作。