我有以下数组
$_POST[0][name]
$_POST[0][type]
$_POST[0][planet]
...
$_POST[1][name]
$_POST[1][type]
$_POST[1][planet]
现在我想计算所有的$_POST[x][type]。怎么做呢?
(如果我将反转多维数组,它将工作我猜像这样:)
$count = count($_POST['type']);
如何计算原始结构中的"类型"?
$type_count = 0;
foreach($arr as $v) {
if(array_key_exists('type', $v)) $type_count++;
}
在您的例子中,这行得通:
$count = call_user_func_array('array_merge_recursive', $_POST);
echo count($count['name']); # 2
$count = 0;
foreach ($_POST as $value) {
if (isset($value['type']) {
$count++;
}
}
PHP5.3 style
$count = array_reduce (
$_POST,
function ($sum, $current) {
return $sum + ((int) array_key_exists('type', $current));
},
0
);
使用set操作:
$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]);}));