PHP count items in a multi-dimensional array

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

    You can use array_walk_recursive() to get access to all of the leaf nodes in an array structure.

    Something akin to this should work for you:

     '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')));
    
    function countleafkeys($value, $key, $userData)
    {
      echo "$key\n";
      if(!isset($userData[$key])) {
        $userData[$key] = 1;
      } else {
        $userData[$key]++;
      }
    }
    
    $result = array();
    array_walk_recursive($data, 'countleafkeys', &$result);
    
    print_r($result);
    

    Outputs:

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

提交回复
热议问题