码迷,mamicode.com
首页 > 编程语言 > 详细

PHP 数组去除重复平且记录值

时间:2017-09-14 18:40:59      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:else   result   index   str   []   div   ber   ace   for   

$arr = array(
    array(
        ‘user_id‘ => 100,
        ‘goods_id‘ => 10,
        ‘number‘ => 1,
    ),
    array(
        ‘user_id‘ => 102,
        ‘goods_id‘ => 10,
        ‘number‘ => 1,
    ),
    array(
        ‘user_id‘ => 102,
        ‘goods_id‘ => 10,
        ‘number‘ => 1,
    ),
    array(
        ‘user_id‘ => 102,
        ‘goods_id‘ => 10,
        ‘number‘ => 1,
    ),
);
$container = array();
$result = array();
foreach ($arr as $item) {
  $key = $item[‘user_id‘] . ‘_‘ . $item[‘goods_id‘];
   if (empty($container[$key])) {
       $container[$key] = $item[‘number‘];
   }else {
        $container[$key] += $item[‘number‘];
   }
}
foreach ($container as $key => $item) {
      list($user_id, $goods_id) = explode(‘_‘, $key);
     $result[] = array(‘user_id‘ => $user_id, ‘goods_id‘ => $goods_id, ‘number‘ => $item);
 
}
运行结果

array (
  0 => 
  array (
    ‘user_id‘ => ‘100‘,
    ‘goods_id‘ => ‘10‘,
    ‘number‘ => 1,
  ),
  1 => 
  array (
    ‘user_id‘ => ‘102‘,
    ‘goods_id‘ => ‘10‘,
    ‘number‘ => 3,
  ),
)
 

PHP 数组去除重复平且记录值

标签:else   result   index   str   []   div   ber   ace   for   

原文地址:http://www.cnblogs.com/xiaoqiangjun/p/7521451.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!