我目前有以下数组:
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 ) )
我正在尝试使用各种组值作为键创建一个新数组,然后计算每组中有多少以提供以下内容:
Array ( [1] => 2 [2] => 2 [3] => 1 )
我试图使用以下内容,但是我收到了未定义的索引警告:
$newArr = array(); foreach ($details['user_groups'] as $key => $value) { $newArr[$value['user_groups']]++; }
(我确实检查了SO的其他答案,但找不到试图做同样的事情)
这可以通过简单的迭代完成:
$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()
函数以从2D数组聚合内部键,这可以简化为:
$counts = array_count_values(array_flip(array_column($array,'group')));