2015-12-18 30 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'數組),這是我所做的,並且對我很有用。但我不知道這是否正確?