PHP count items in a multi-dimensional array

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

    Here is my recursive variant:

    $arr = array(
        '0' => array(
            '0' => array('2011-11-18 00:00:00' => 'C'),
            '1' => array('2011-11-18 00:00:00' => 'I'),
            '2' => array('2011-11-18 00:00:00' => 'S')
        ),
        '1' => array(
            '0' => array('2011-11-22 00:00:00' => 'C'),
            '1' => array('2011-11-22 00:00:00' => 'S')
        ),
        '2' => array(
            '0' => array(
                '0' => array('2011-11-22 00:00:00' => 'D')
            )
        )
    );
    
    function count_values($array, &$result = array(), $counter = 0)
    {
        foreach ($array as $key => $data)
        {
            if (is_array($data))
            {
                count_values($data, $result, $counter);
            }
            else
            {
                array_key_exists($key, $result) ? $result[$key]++ : $result[$key] = 1;
            }
        }
    
        return $result;
    }
    
    print_r(count_values($arr));
    

    This will return:

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

提交回复
热议问题