PHP count items in a multi-dimensional array

前端 未结 9 1055
走了就别回头了
走了就别回头了 2021-01-11 19:54

As you can see from the following array, there are three elements that appear on Nov 18, and another two elements that appear on Nov 22. Can someone tell me how I can retri

相关标签:
9条回答
  • 2021-01-11 20:35

    Assuming that your array example is representative:

    foreach ($array as $key => $value)
    {
       echo count($value) . "<br />";
    }
    

    Will echo the number of arrays within each of the main array items. In your example, that would also be the number of entries for each date.

    This does not of course check the dates themselves

    0 讨论(0)
  • 2021-01-11 20:36

    If you want count the items unidimensional and bidimensional you can try:

    echo 'Size of unidimensional is: '.count($celda).'<br/>';
    
    echo 'Size of bidimensional is: '.count($celda[0]).'<br/>';
    
    0 讨论(0)
  • 2021-01-11 20:42

    the posted answers are correct for your representative example, but i would like to add another solution, that will work regardless how many nested arrays you may create. it iterates the array recursively and counts all items in all sub-arrays.

    it returns the total count of items in the array. in the second argument you can specify an array reference which will contain the count per unique key in the (nested) array(s).

    example:

    <?php
    $deeply_nested = array(
                         'a' => 'x',
                         'b' => 'x',
                         'c' => 'x',
                         'd' => array(
                             'a' => 'x',
                             'b' => 'x',
                             'c' => array(
                                 'a' => 'x',
                                 'b' => 'x'
                             ),
                             'e' => 'x'
                        ) 
                    );
    
    function count_nested_array_keys(array &$a, array &$res=array()) {
        $i = 0;
        foreach ($a as $key=>$value) {
            if (is_array($value)) {
                 $i += count_nested_array_keys($value, &$res);
            }
            else {
                 if (!isset($res[$key]) $res[$key] = 0;
    
                 $res[$key]++;
                 $i++;
            }
        }
        return $i;
    }
    
    $total_item_count = count_nested_array_keys($deeply_nested, $count_per_key);
    
    echo "total count of items: ", $total_item_count, "\n";
    echo "count per key: ", print_r($count_per_key, 1), "\n";
    

    results in:

    total count of items: 8
    count per key: Array
    (
        [a] => 3
        [b] => 3
        [c] => 1
        [e] => 1
    )
    
    0 讨论(0)
提交回复
热议问题