>  기사  >  백엔드 개발  >  php关于count函数求解释解决方案

php关于count函数求解释解决方案

WBOY
WBOY원래의
2016-06-13 10:37:40799검색

php关于count函数求解释

PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->$food = array('fruits' => array('orange', 'banana', 'apple'),                            'veggie' => array('carrot', 'collard', 'pea'));              // recursive count              echo count($food, COUNT_RECURSIVE); // output 8

怎么是输出8的呢?不是6么?

------解决方案--------------------
递归累计啊,要加上一维统计2,
------解决方案--------------------
COUNT_RECURSIVE 字面意思就是递归统计啊……

If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array.

顺着手册的意思理解吧,,,如果你的需求不适用,自写函数咯,
------解决方案--------------------
别人给你的东西不是总能合你意的,经常是需要自己动下手的
count($food, COUNT_RECURSIVE) 返回的是所有的节点数量
而你需要的只是叶节点的数量
PHP code
$food = array(  'fruits' => array('orange', 'banana', 'apple'),  'veggie' => array('carrot', 'collard', 'pea'));function leay_count($ar) {  $r = 0;  foreach($ar as $item) {    if(is_array($item)) $r += leay_count($item);    else $r++;  }  return $r;}echo leay_count($food);<div class="clear">
                 
              
              
        
            </div>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.