时间:2021-07-01 10:21:17 帮助过:3人阅读
如下有两数组,求解该如何按条件合并为一个数组。
$item_1 = array(
[0]=> array(
'goods_id'=>1,
'price'=>1,
'goods_name'=>'商品1',
'goods_attr_id'=>'1',
'num'=>1,
),
[1]=> array(
'goods_id'=>2,
'price'=>10,
'goods_name'=>'测试商品2',
'goods_attr_id'=>'3',
'num'=>2,
),
[2]=> array(
'goods_id'=>3,
'price'=>20,
'goods_name'=>'测试商品3',
'goods_attr_id'=>'4',
'num'=>3,
),
);
$item_2 = array(
[0]=> array(
'goods_id'=>1,
'price'=>1,
'goods_name'=>'商品1',
'goods_attr_id'=>'1,2',
'num'=>1,
),
[1]=> array(
'goods_id'=>2,
'price'=>10,
'goods_name'=>'测试商品2',
'goods_attr_id'=>'3',
'num'=>2,
),
[2]=> array(
'goods_id'=>4,
'price'=>30,
'goods_name'=>'测试商品4',
'goods_attr_id'=>'5',
'num'=>1,
),
);
合并数据为一个数组,如果属性相等的则增加数量,商品ID,属性不同的商品则不合并。
如下有两数组,求解该如何按条件合并为一个数组。
$item_1 = array(
[0]=> array(
'goods_id'=>1,
'price'=>1,
'goods_name'=>'商品1',
'goods_attr_id'=>'1',
'num'=>1,
),
[1]=> array(
'goods_id'=>2,
'price'=>10,
'goods_name'=>'测试商品2',
'goods_attr_id'=>'3',
'num'=>2,
),
[2]=> array(
'goods_id'=>3,
'price'=>20,
'goods_name'=>'测试商品3',
'goods_attr_id'=>'4',
'num'=>3,
),
);
$item_2 = array(
[0]=> array(
'goods_id'=>1,
'price'=>1,
'goods_name'=>'商品1',
'goods_attr_id'=>'1,2',
'num'=>1,
),
[1]=> array(
'goods_id'=>2,
'price'=>10,
'goods_name'=>'测试商品2',
'goods_attr_id'=>'3',
'num'=>2,
),
[2]=> array(
'goods_id'=>4,
'price'=>30,
'goods_name'=>'测试商品4',
'goods_attr_id'=>'5',
'num'=>1,
),
);
foreach ($item_1 as $key => $value) {
$arr[$value['goods_id'].'_'.$value['goods_attr_id']]=$value;
}
foreach ($item_2 as $key => $value) {
if(empty($arr[$value['goods_id'].'_'.$value['goods_attr_id']])){
$arr[$value['goods_id'].'_'.$value['goods_attr_id']]=$value;
}else{
$arr[$value['goods_id'].'_'.$value['goods_attr_id']]['num']=$arr[$value['goods_id'].'_'.$value['goods_attr_id']]['num']+$value['num'];
}
}
var_dump($arr);
先排序,相同的排在一起,再计数。
看着挺像EC的,先按照goods_id分组,然后去重合并,具体的做法你可以搜搜php数组函数,有很多 你将这个组每个函数都玩一遍 打印看看就学会他们的用途了