PHP count items in a multi-dimensional array

前端 未结 9 1059
走了就别回头了
走了就别回头了 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:17

    Does this work for what you need?

    $dates = array(array(array("2011-11-18 00:00:00" => C), array("2011-11-18 00:00:00" => I),array
    ("2011-11-18 00:00:00" => S)),
    array(array("2011-11-22 00:00:00" => C), array("2011-11-22 00:00:00" => S)));
    
    $date_count = array();  // create an empty array
    
    foreach($dates as $date) {  // go thought the first level
        foreach($date as $d) {  // go through the second level
            $key = array_keys($d);  // get our date
            // here we increment the value at this date
            // php will see it as 0 if it has not yet been initialized
            $date_count[$key[0]]++;
        }
    }
        // show what we have
    print_r($date_count);
    

    Prints:

    Array ( [2011-11-18 00:00:00] => 3 [2011-11-22 00:00:00] => 2 )
    

    Note: this assumes that you will always be getting data as you structured your array and that each date will be formatted the same. If you can't assume each date will be formatted, this would be a simple conversion using the date() function. If you can't assume that you will get data structured exactly like this, the best way to tackle that would probably be through a recursive function.

提交回复
热议问题