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"}]
请问该怎么弄啊
展开
 我来答
莫路草根
2015-04-29 · TA获得超过4102个赞
知道大有可为答主
回答量:4184
采纳率:85%
帮助的人:1031万
展开全部
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));
百度网友8041235
推荐于2016-11-06 · TA获得超过227个赞
知道小有建树答主
回答量:334
采纳率:0%
帮助的人:228万
展开全部
$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);
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式