在PHP中计算关联数组中值的出现次数

3
请帮我计算这个关联数组中值出现的次数。
<?php
$employees = array(
   1 => array(
       'name' => 'Jason Alipala',
       'employee_id' => 'G1001-05',
       'position' => 1             
   ),
   2 => array(
       'name' => 'Bryann Revina',
       'employee_id' => 'G1009-03',
       'position' => 2           
   ),
   3 => array(
       'name' => 'Jeniel Mangahis',
       'employee_id' => 'G1009-04',
       'position' => 2
   ),
   4 => array(
       'name' => 'Arjay Bussala',
       'employee_id' => 'G1009-05',
       'position' => 3        
   ),
   5 => array(
       'name' => 'Ronnel Ines',
       'employee_id' => 'G1002-06',
       'position' => 3           
   )
   );

?>

这是我从fake_db.php中的代码,我在index.php中使用include_once。我想要计算'position'相同值的出现次数。例如:1 = 1,2 = 2,3 = 2。
此外,还有另一个名为$positions的数组...
$positions = array(
    1 => 'TL',
    2 => 'Programmer',
    3 => 'Converter');

这个数组是我用来与$employees数组中的“position”进行比较的。

任何帮助都将不胜感激,谢谢!


请分享一下你目前为止尝试过的内容,展示你的尝试成果。 - Narendrasingh Sisodia
6个回答

15

array_count_valuesarray_column的组合(PHP 5 >= 5.5.0,PHP 7)应该可以工作 -

$counts = array_count_values(
    array_column($employees, 'position')
);

输出

array(3) {
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(2)
}

更新

$final = array_filter($counts, function($a) {
   return $a >= 2;
});

输出

array(2) {
  [2]=>
  int(2)
  [3]=>
  int(2)
}

演示


1
请指定版本,因为array_column可能在5.5中使用。 - Narendrasingh Sisodia
我收到了你的代码,但我想要显示的不是数组,只是一个变量。例如,我只想显示在“位置”类别上有多少个值为“2”的变量。谢谢。 - MDB

1

array_column - 从数组中返回单个列的值。array_count_values - 统计数组中所有值的数量。

$positions = array_column($employees, 'position');
print_r(array_count_values($positions));

输出

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

0
嵌套循环可以完成这项工作。取一个数组,将键作为实际值,并将键中的值作为该键的计数器。 如果键存在于数组中,那么它就具有值,只需递增即可;否则,将1赋值给初始化具有值1的键。
例如:1 => 1的计数器(出现次数)
 $arrayCounter=0;

 foreach($employees as $value){
     foreach($value as $data){
          $position = $data['position'];
        if(array_key_exists($position,$arrayCounter)){
             $arrayCounter[$position] = arrayCounter[$position]++;
        }
       else{ 
           $arrayCounter[$position] = 1;  
       }
   }

0

这很简单。数组$employees是您提供的数组。您可以使用以下代码:

$data = array();

foreach($employees as $employee) {
    if(isset($data[$employee['position']])) {
        $data[$employee['position']]++;
    } else {
        $data[$employee['position']] = 1;
    }
}

echo "<pre>";
print_r($data);
echo "</pre>";

这将输出:

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

0
        $total = 0;
        foreach($employees as $eNum => $value){
            if($aEmployees[$eNum]['position'] == $key){
                $total++;
            }
        }
        echo $total;

这些代码位于一个函数中,该函数在foreach循环的每次迭代(另一个名为“$positions”的数组)中被调用。 $key是一个变量,它包含来自foreach循环('$positions'数组)的值.. 这就是我所做的,它对我有效。但我不知道这是否是正确的方式?

0

您可以使用预定义的php函数array_count_value()来实现您的目标。 您可以在这里查看结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接