php關於count函數求解釋解決方案

來源:互聯網
上載者:User
php關於count函數求解釋
PHP code
$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);
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.