Php Group数组按值和计数组项

时间:2017-01-04 16:39:26

标签: php mysql arrays

我正在创建一个通知系统。下面显示的结果将返回特定用户的所有通知。我想通过'notify_id'对数组进行分组,并计算组中的每个项目。

这样我就会:

Jack Bill 现在关注你了”, John Doe 对你的帖子2发表评论“, “ John Doe和另外2人评论了你的帖子1”

Array ( [0] => 
Array ( [id] => 1 
        [user_id] => 10 
        [type] => follow 
        [notify_id] => 13 
        [notify_date] => 1483444712 
        [firstname] => Jack 
        [surname] => Bill 
        [picture] => ) 



       [1] => 
Array ( [id] => 10 
        [user_id] => 10 
        [type] => comment 
        [notify_id] => 2 
        [notify_date] => 1482159309 
        [firstname] => John
        [surname] => Doe 
        [picture] => ) 

        [2] => 
Array ( [id] => 8 
        [user_id] => 10 
        [type] => comment 
        [notify_id] => 1 
        [notify_date] => 1482159219 
        [firstname] => John 
        [surname] => Doe 
        [picture] => ) 

        [3] => 
Array ( [id] => 6 
        [user_id] => 16 
        [type] => comment 
        [notify_id] => 1 
        [notify_date] => 1482159129 
        [firstname] => James 
        [surname] => Canon 
        [picture] => ) 

        [4] => 
Array ( [id] => 5 
        [user_id] => 14 
        [type] => comment 
        [notify_id] => 1 
        [notify_date] => 1482159079 
        [firstname] => Sharon 
        [surname] => Abba 
        [picture] => )  )

1 个答案:

答案 0 :(得分:1)

你有两个问题,我会尽力回答这两个问题:

  

我想通过' notify_id' ...

对数组进行分组

假设您的阵列名称为$a

$return = array();
foreach($a as $val) {
    if (!isset($return[$val['notify_id']])) {
        $return[$val['notify_id']] = array();
    }
    $return[$val['notify_id']][] = $val;
}
print_r($return); // <-- Your array is grouped by notify_id
  

...并且还计算组中的每个项目。

现在,您在notify_id中按$return进行了分组,因此:

foreach($return as $k => $v) {
    echo count($v) . ' values are present for notify #' . $k;
    // It will display something like: 10 values are present for notify #1
}

希望它会有所帮助,祝你好运!