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

时间:2015-12-18 06:29:55

标签: php arrays

请帮我详细说明如何计算此关联数组中值的出现次数。

<?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 。我想计算“位置”的相同值的出现次数。 1 = 1,2 = 2,3 = 2

此外,还有另一个名为$ positions ...

的数组
$positions = array(
    1 => 'TL',
    2 => 'Programmer',
    3 => 'Converter');

这个数组是我比较$ employees数组的'position'的地方。

感谢任何帮助,谢谢!

6 个答案:

答案 0 :(得分:5)

array_count_values&amp;的组合array_column (PHP 5&gt; = 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)
}

Demo

答案 1 :(得分:0)

嵌套循环将完成这项工作。取一个数组,将密钥保存为实际值,并将密钥中的值保存为该密钥的COUNTER。 如果密钥存在于数组中,则意味着它只有增量值,否则赋值1以初始化值为1的密钥。

e.g。 1 =&gt;计数器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;  
       }
   }

答案 2 :(得分:0)

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

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

输出

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

答案 3 :(得分: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
)

答案 4 :(得分:0)

你可以使用array_count_value()预定义php函数来实现你的目标。 你可以看到结果here

答案 5 :(得分:0)

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

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

相关问题