2011-10-10 33 views
0

的第二阵列键我有以下阵列PHP - 计数()在多维数组

$_POST[0][name] 
$_POST[0][type] 
$_POST[0][planet] 
... 
$_POST[1][name] 
$_POST[1][type] 
$_POST[1][planet] 

现在我想指望所有的$ _ POST [X] [类型]。怎么做?

如果我将扭转多维数组,它的工作我想这样:)

$count = count($_POST['type']); 

我怎么能算在原来的结构中的“类型”?

回答

4
$type_count = 0; 
foreach($arr as $v) { 
    if(array_key_exists('type', $v)) $type_count++; 
} 
0
$count = 0; 
foreach ($_POST as $value) { 
    if (isset($value['type']) { 
     $count++; 
    } 
} 
0

PHP5.3风格

$count = array_reduce (
    $_POST, 
    function ($sum, $current) { 
     return $sum + ((int) array_key_exists('type', $current)); 
    }, 
    0 
); 
2

在你的情况,这个工程:

$count = call_user_func_array('array_merge_recursive', $_POST); 

echo count($count['name']); # 2 
0

并采用集合操作:

$key = 'type'; 
$tmp = array_map($_POST, function($val) use ($key) {return isset($val[$key]);}); 
$count = array_reduce($tmp, function($a, $b) { return $a + $b; }, 0); 

所以你Ç可以减少array_filter:

$key = 'type'; 
$count = count(array_filter($_POST, function($val) use ($key) { return isset($val[$key]);}));