Php solution for count function

Source: Internet
Author: User
Php PHPcode $ food = array ('Fruits '= & gt; array ('Orange', 'bana', 'apple '), 'veggi' = & gt; array ('php interpretation of the count function
PHP code
  $food = array('fruits' => array('orange', 'banana', 'apple'),                            'veggie' => array('carrot', 'collard', 'pea'));              // recursive count              echo count($food, COUNT_RECURSIVE); // output 8

How does one output 8? Isn't it 6?

------ Solution --------------------
Recursive accumulation. Add one-dimensional statistics 2,
------ Solution --------------------
COUNT_RECURSIVE literally refers to recursive statistics ......

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

Follow the instructions in the manual. if your requirements are not applicable, write a UDF,
------ Solution --------------------
What others give you doesn't always mean to you. you often need to do it by yourself.
Count ($ food, COUNT_RECURSIVE) returns the number of all nodes
What you need is the number of leaf nodes.
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);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.