识别二维数组的行属于 3 组中的 1 组,并计算每组中的出现次数

问题描述 投票:0回答:2

我有这个数组:

Array ( 
    [0] => Array ( [countThis_id] => 1 [icon] => add.gif [url] => add.php)
    [1] => Array ( [countThis_id] => 1 [icon] => add.gif [url] => add.php)
    [2] => Array ( [countThis_id] => 2 [icon] => add.gif [url] => add.php)
    [3] => Array ( [countThis_id] => 2 [icon] => add.gif [url] => add.php)
    [4] => Array ( [countThis_id] => 5 [icon] => add.gif [url] => add.php)
    [5] => Array ( [countThis_id] => 6 [icon] => add.gif [url] => add.php)
    [6] => Array ( [countThis_id] => 7 [icon] => add.gif [url] => add.php)
    [7] => Array ( [countThis_id] => 7 [icon] => add.gif [url] => add.php)     
)

我想计算

countThis_id
值的出现次数,因为它们与预定义组相关。

  • 如果
    1
    ,则在
    count_1
    组总数中添加 1
  • 如果
    2
    ,则在
    count_2
    组总数中添加 1,
  • 如果有任何其他值,则在
    the_Rest
    组总数中加一。

我想要的结果:

Array ( 
    [0] => Array ( [countThis_id] => 1 [icon] => add.gif [url] => add.php)
    [1] => Array ( [countThis_id] => 1 [icon] => add.gif [url] => add.php)
    [2] => Array ( [countThis_id] => 2 [icon] => add.gif [url] => add.php)
    [3] => Array ( [countThis_id] => 2 [icon] => add.gif [url] => add.php)
    [4] => Array ( [countThis_id] => 5 [icon] => add.gif [url] => add.php)
    [5] => Array ( [countThis_id] => 6 [icon] => add.gif [url] => add.php)
    [6] => Array ( [countThis_id] => 7 [icon] => add.gif [url] => add.php)
    [7] => Array ( [countThis_id] => 7 [icon] => add.gif [url] => add.php)   
    [8] => Array ( [count_1] => 2 [count_2] => 2 [the_Rest] => 4)   
)
php arrays multidimensional-array grouping counting
2个回答
0
投票
$result = array('count_1' => 0, 'count_2'=>0, 'the_Rest'=>0);
foreach($array as $arr){
   if($arr['countThis_id'] == 2){
     $result['count_1']++;
   }
   else if($arr['countThis_id'] == 1){
     $result['count_1']++;
   }
   else {
     $result['the_rest']++;
   }
}

array_push($array, $result);
var_dump($array);

对于排序,您可以使用 array_multisort()


0
投票

三向比较运算符(又名:“宇宙飞船运算符”)返回

-1
0
1
。您的任务需要将数据识别为三个不同的组。因为您似乎正在评估大于零的整数,并且需要一组
1
2
,然后是任何其他数字,所以您可以将每个遇到的数字与
2
进行比较,并利用映射数组来消除对
if
块。

代码:(演示

$buckets = [-1 => 'count_1', 0 => 'count_2', 1 => 'the_Rest'];
$totals = array_fill_keys($buckets, 0);
foreach ($array as ['countThis_id' => $id]) {
    ++$totals[$buckets[$id <=> 2]];
}
$array[] = $totals;
var_export($array);

或者类似地,使用

match()
演示

$totals = ['count_1' => 0, 'count_2' => 0, 'the_Rest' => 0];
foreach ($array as ['countThis_id' => $id]) {
    ++$totals[match ($id) {
        1 => 'count_1',
        2 => 'count_2',
        default => 'the_Rest',
    }];
}
$array[] = $totals;
var_export($array);
© www.soinside.com 2019 - 2024. All rights reserved.