计算多维数组中的值

计算多维数组中的值

本文介绍了计算多维数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下数组:

Array(
        [0] => Array
            (
                [user] => Name 1
                [group] => 1
            )
        [1] => Array
            (
                [user] => Name 2
                [group] => 1
            )
        [2] => Array
            (
                [user] => Name 3
                [group] => 2
            )
        [3] => Array
            (
                [user] => Name 4
                [group] => 2
            )
        [4] => Array
            (
                [user] => Name 5
                [group] => 3
            )
)

我正在尝试创建一个以各种 group 值作为键的新数组,然后计算每个组中有多少,以给出以下内容:

I am attempting to create a new array with the various group values as the key, then count how many are in each group to give the following:

Array
(
    [1] => 2
    [2] => 2
    [3] => 1
)

我尝试使用以下内容,但收到未定义的索引警告:

I have attempted to use the following, however I get undefined index warnings:

$newArr = array();
foreach ($details['user_groups'] as $key => $value) {
        $newArr[$value['user_groups']]++;
}

(我确实检查了其他答案,但是找不到试图做同样的事情)

(I did check SO for other answers, however couldn't find one attempting to do the same)

推荐答案

这可以通过一个简单的迭代来完成:

This can be done with a simple iteration:

$counts = array();
foreach ($array as $key=>$subarr) {
  // Add to the current group count if it exists
  if (isset($counts[$subarr['group']]) {
    $counts[$subarr['group']]++;
  }
  // or initialize to 1 if it doesn't exist
  else $counts[$subarr['group']] = 1;

  // Or the ternary one-liner version
  // instead of the preceding if/else block
  $counts[$subarr['group']] = isset($counts[$subarr['group']]) ? $counts[$subarr['group']]++ : 1;
}

PHP 5.5 更新

在 PHP 5.5 中,增加了 array_column() 函数从二维数组聚合一个内部键,这可以简化为:

Update for PHP 5.5

In PHP 5.5, which has added the array_column() function to aggregate an inner key from a 2D array, this can be simplified to:

$counts = array_count_values(array_flip(array_column($array, 'group')));

这篇关于计算多维数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 09:25