2012-04-25 70 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); 
     } 
    } 

试试这个..

感谢