2015-12-18 34 views
1

请帮我如何在这个关联数组计数的值的出现。计数出现

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

此外,还有一个名为$位置的另一种阵列...

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

这个数组是我比较从$员工阵列的 '位置' 。

任何帮助表示赞赏,谢谢!

+0

你到目前为止试过的东西发布你的尝试 –

回答

3

& array_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) 
} 

Demo

+1

Bose也指定了版本。作为'array_column'可能会在** 5.5 ** –

+0

是使用..忘记... :) –

+0

我得到你的代码,但我想要显示的不是数组。只是一个变量..例如,我只想显示“位置”类别中有多少个值为'2'。谢谢。 – MDB

0

嵌套循环将完成这项工作。取一个数组,将该键保存为实际值,并将该键中的值保存为该键的COUNTER。 如果键阵列,这意味着它具有的值只是增加别的分配1来初始化值1

例如键存在的1(出现)1 =>计数器

组合的 array_count_values
$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

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

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

输出

Array 
(
    [1] => 1 
    [2] => 2 
    [3] => 2 
) 
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

您可以使用array_count_value()预先定义的PHP函数来获取你的目标。 你可以看到导致here

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

这些代码是一个被称为在foreach循环的每次迭代函数内(另一阵列名为“$位置”).. $关键是包含值的变量那foreach循环('$ positions'数组),这是我所做的,并且对我很有用。但我不知道这是否正确?