2015-01-07 39 views
1

我已經寫了下面的函數,它需要一個2維數組並返回一個鍵發生的次數,但感覺就像我可能在這裏重新發明輪子,有沒有簡單的方法?數組中的鍵

function countKeys($array, $key) 
{ 
    $results = array(); 

    foreach($array as $row) 
    { 
    if (array_key_exists($row[$key], $results)) 
    { 
     $results[$row[$key]] += 1; 
    } 
    else 
    { 
     $results[$row[$key]] = 1; 
    } 
    } 

    return $results; 
} 
+0

我已更新我的答案。它有點清潔,可能對您有所幫助。 –

回答

1

要計算一個二維數組鍵與搜索我會做到這一點 -

function countKeys($array,$search){ 
    $key_count = array(); // new array 
    foreach($array as $record) { 
     $keys = array_keys($record); 
     foreach($keys as $key){ 
      if($key == $search){ // check against the search term 
       array_push($key_count, $key); // add the key to the new array 
      } 
     } 
    } 
    return count($key_count); // just count the new array 
} 
echo countKeys($records, 'last_name'); 

EXAMPLE

array_keys() count()

+0

OP狀態2維數組。 – AbraCadaver

+0

編輯@AbraCadaver。這工作沒有PHP 5.5+ –