Multi-Dimensional array count in PHP

后端 未结 7 1606
感情败类
感情败类 2020-12-20 11:16

I have a multi-dimentional array set up as follows

array() {
    [\"type1\"] =>
    array() {
        [\"ticket1\"] =>
        array(9) { 
                    


        
7条回答
  •  再見小時候
    2020-12-20 11:35

    A bit late but this is a clean way to write it.

    $totalTickets = array_sum(array_map("count", $tickets));
    

    Assuming $tickets is your multi-dimensional array.

    I've expanded the code to give an explained example because array_map might be new to some

    $tickets = array(
        "type1" => array(
            "ticket1" => array(),
            "ticket2" => array(),
            "ticket3" => array(),
        ),
        "type2" => array(
            "ticket4" => array(),
            "ticket5" => array(),
            "ticket6" => array(),
            "ticket7" => array(),
        ),
        "type3" => array(
            "ticket8" => array()
        )
    );
    
    // First we map count over every first level item in the array
    // giving us the total number of tickets for each type.
    $typeTotals = array_map("count", $tickets);
    
    // print_r($typeTotals);
    // $type_totals --> Array (
    //                       [type1] => 3,
    //                       [type2] => 4,
    //                       [type3] => 1 
    //                  )
    
    //Then we sum the values of each of these
    $totalTickets = array_sum($typeTotals);
    
    print($totalTickets);
    // $totalTickets --> 8
    

    So because we don't care about the intermediate result of each type we can feed the result into array_sum

    $totalTickets = array_sum(array_map("count", $tickets));
    

提交回复
热议问题