php循环出来的数组向相合并并且相加
比如这是我查出来的结果["goods_price":"1000","goods_name":"老白干","order_id":"1","order_sn":"000000...
比如这是我查出来的结果
["goods_price":"1000","goods_name":"老白干","order_id":"1","order_sn":"00000001"},{"goods_price":"1200","goods_name":"茅台","order_id":"1","order_sn":"00000001"},
{"goods_price":"500","goods_name":"五粮液","order_id":"2","order_sn":"00000002"}]
我想把订单id一样的合并 价格相加 :
[{goods_price":"2200","goods_name":"老白干/茅台","order_id":"1","order_sn":"00000001"},
{goods_price":"500","goods_name":"五粮液","order_id":"2","order_sn":"00000002"}]
请问该怎么弄啊 展开
["goods_price":"1000","goods_name":"老白干","order_id":"1","order_sn":"00000001"},{"goods_price":"1200","goods_name":"茅台","order_id":"1","order_sn":"00000001"},
{"goods_price":"500","goods_name":"五粮液","order_id":"2","order_sn":"00000002"}]
我想把订单id一样的合并 价格相加 :
[{goods_price":"2200","goods_name":"老白干/茅台","order_id":"1","order_sn":"00000001"},
{goods_price":"500","goods_name":"五粮液","order_id":"2","order_sn":"00000002"}]
请问该怎么弄啊 展开
2个回答
展开全部
header("Content-type: text/html; charset=utf-8");
$str = '[{"goods_price":"1000","goods_name":"老白干","order_id":"1","order_sn":"00000001"},{"goods_price":"1200","goods_name":"茅台","order_id":"1","order_sn":"00000001"},
{"goods_price":"500","goods_name":"五粮液","order_id":"2","order_sn":"00000002"}]';
$str = json_decode($str,true);
$res = array();
foreach($str as $item) {
if(! isset($res[$item['order_id']])){
$res[$item['order_id']] = $item;
}
else{
$res[$item['order_id']]['goods_price'] += $item['goods_price'];
$res[$item['order_id']]['goods_name'] .= '/'. $item['goods_name'];
}
}
print_r(array_values($res));
展开全部
$json = '[{"goods_price":"1000","goods_name":"老白干","order_id":"1","order_sn":"00000001"},{"goods_price":"1200","goods_name":"茅台","order_id":"1","order_sn":"00000001"},{"goods_price":"500","goods_name":"五粮液","order_id":"2","order_sn":"00000002"}]';
$array = json_decode($json, 1);
$last = array();
foreach ($array as $index => $value) {
if (isset($last[$value['order_id']])) {
$last[$value['order_id']]['goods_price'] += $value['goods_price'];
if ($last[$value['order_id']]['goods_name'] !== $value['goods_name']) {
$last[$value['order_id']]['goods_name'] .= '/' . $value['goods_name'];
}
} else {
$last[$value['order_id']] = $value;
}
}
$last_json = json_encode($last, JSON_UNESCAPED_UNICODE);
$last_json = stripslashes($last_json);
var_dump($last_json);
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询