PHP递归数组计数 [英] Php recursive array counting
问题描述
我想写这计算数组元素递归函数。
但结果是假的。
什么会不会是什么问题?
$模式=阵列(
'格'=>阵列(
类= GT; '行',
'格'=>阵列(
'跨'=>阵列(
钥匙= GT; '产品名称'
)
VAL'=> '肥皂'
)
层=>阵列(
'跨'=>阵列(
钥匙= GT; '产品名称'
)
VAL'=> '球'
)
)
);功能count_r($数组,$ I = 0){
的foreach($数组作为$ K){
如果(is_array($ K)){$ I + = count_r($ K,计数($ K)); }
其他{$ I ++; }
}
$回报我;
}回声count_r($模式);
PHP有此目的,称为内置方法计数()
。如果没有任何额外的参数传递,计数()
返回数组键上的第一级的数量。但是,如果你通过第二个参数来计数方法计数($模式,真实)
,那么结果将是多维数组中的键的总数。标记为正确只迭代第一级和第二级阵列的响应,如果该阵列中有第三个孩子,它不会返回正确的答案。
这可以写成一个递归函数,如果你真的想编写自己的计数()方法,虽然。
I'm trying to write a function which counts array elements recursively.
But result is false.
What could it be problem?
$schema = array(
'div' => array(
'class' => 'lines',
'div' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Soap'
),
'layer' => array(
'span' => array(
'key' => 'Product Name'
),
'val' => 'Ball'
)
)
);
function count_r($array, $i = 0){
foreach($array as $k){
if(is_array($k)){ $i += count_r($k, count($k)); }
else{ $i++; }
}
return $i;
}
echo count_r($schema);
PHP has a built-in method for this purpose, called count()
. If passed without any additional parameters, count()
returns the number of array keys on the first level. But, if you pass a second parameter to the count method count( $schema, true )
, then the result will be the total number of keys in the multi-dimensional array. The response marked as correct only iterates first and second level arrays, if you have a third child in that array, it will not return the correct answer.
This could be written as a recursive function, if you really want to write your own count() method, though.
这篇关于PHP递归数组计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!