PHP 以商品维度 去重user_id

3p3xtti1
  • 1
新手上路,请多包涵
$a    = [
    ['name' => 'test', 'user_id' => 1, 'goods_id' => 2],
    ['name' => 'test', 'user_id' => 1, 'goods_id' => 2],
    ['name' => 'test', 'user_id' => 2, 'goods_id' => 2],
    ['name' => 'test', 'user_id' => 3, 'goods_id' => 2],
    ['name' => 'test', 'user_id' => 3, 'goods_id' => 3],
];
$data = [];
foreach ($a as $v) {
    $key = $v['goods_id'];
    !isset($data[$key]['pay_num']) && $data[$key]['pay_num'] = 0;
    !isset($data[$key]['goods_id']) && $data[$key]['goods_id'] = 0;
    !isset($data[$key]['user_id']) && $data[$key]['user_id'] = 0;
    $data[$key]['goods_id'] = $v['goods_id'];
    $data[$key]['user_id']  = $v['user_id'];
    $data[$key]['pay_num']  = 1;
}
$data = array_values($data);

比如这组二维数组数据 统计下单人数 商品id 一样 用户一样 我想得到pay_num=1 该如何处理,

最后想得到的结果是

[
  {
    "pay_num": 3,
    "goods_id": 2
  },
  {
    "pay_num": 1,
    "goods_id": 3
  }
]
回复
阅读 338
1 个回答

这玩意儿说简单也简单,只要把逻辑理清,怎么写就看自己了:

$goods = $res =[];
foreach ($a as $value) {
    $goods[$value['goods_id']][$value['user_id']] = $value['user_id'];    
}

print_r($goods);
foreach ($goods as $goodsId => $userIds) {
    $res[] = ['goods_id' => $goodsId, 'pay_num' => count($userIds)];
}

print_r($res);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏