2012-04-25 66 views
1

我想知道我是否可以解釋這一點。PHP:計算數組中外觀的特定值

我有一個多維數組,我想獲得該出現的數組

下面我顯示陣列的片段特定值的計數。我只是檢查profile_type

所以我想在陣列中顯示profile_type的計數

編輯

對不起,我忘了已經提到的東西,不是其主要的事情,我需要的數profile_type == p

Array 
(
    [0] => Array 
     (
      [Driver] => Array 
       (
        [id] => 4 
        [profile_type] => p      
        [birthyear] => 1978 
        [is_elite] => 0 
       ) 
     ) 
     [1] => Array 
     (
      [Driver] => Array 
       (
        [id] => 4 
        [profile_type] => d      
        [birthyear] => 1972 
        [is_elite] => 1 
       ) 
     ) 

) 

回答

2

簡單的解決方案與RecursiveArrayIterator,所以你不必在意尺寸:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); 

$counter = 0 
foreach ($iterator as $key => $value) { 
    if ($key == 'profile_type' && $value == 'p') { 
    $counter++; 
    } 
} 
echo $counter; 
+0

對不起,我編輯了需要統計的問題profile_type == p – 2012-04-25 12:37:04

+0

好的,我編輯了答案 – 2012-04-25 12:39:14

0

像這樣的東西可能工作...

$counts = array(); 
foreach ($array as $key=>$val) { 
    foreach ($innerArray as $driver=>$arr) { 
     $counts[] = $arr['profile_type']; 
    } 
} 

$solution = array_count_values($counts); 
+0

對不起我已經編輯我需要的計算問題profile_type == p – 2012-04-25 12:36:56

0

我會做這樣的事情:

$profile = array(); 
foreach($array as $elem) { 
    if (isset($elem['Driver']['profile_type'])) { 
     $profile[$elem['Driver']['profile_type']]++; 
    } else { 
     $profile[$elem['Driver']['profile_type']] = 1; 
    } 
} 
print_r($profile); 
0

您也可以使用array_walk ($ array,「test」)並定義一個函數「test」,它檢查數組中的每個項目是否爲'type',並遞歸調用array_walk($ arrayElement,「test」)類型爲'array'的項目,否則檢查條件。如果條件滿足,則增加一個計數。

0

嗨您可以從多dimensiona陣列得到profuke_type == P的計數

$arr = array(); 
    $arr[0]['Driver']['id'] = 4; 
    $arr[0]['Driver']['profile_type'] = 'p'; 
    $arr[0]['Driver']['birthyear'] = 1978; 
    $arr[0]['Driver']['is_elite'] = 0; 


    $arr[1]['Driver']['id'] = 4; 
    $arr[1]['Driver']['profile_type'] = 'd'; 
    $arr[1]['Driver']['birthyear'] = 1972; 
    $arr[1]['Driver']['is_elite'] = 1; 

    $arr[2]['profile_type'] = 'p'; 
    $result = 0; 
    get_count($arr, 'profile_type', 'd' , $result); 
    echo $result; 
    function get_count($array, $key, $value , &$result){ 
     if(!is_array($array)){ 
      return; 
     } 

     if($array[$key] == $value){ 
      $result++; 
     } 

     foreach($array AS $arr){ 
      get_count($arr, $key, $value , $result); 
     } 
    } 

試試這個..

感謝