PHP中的多维数组计数

Kit*_*nes 19 php multidimensional-array

我有一个多维数组,如下所示

array() {
    ["type1"] =>
    array() {
        ["ticket1"] =>
        array(9) { 
           // ticket details here
        }
        ["ticket2"] =>
        array(10) { 
           // ticket details here
        }
        ["ticket3"] =>
        array(9) { 
           // ticket details here
        }
    }
    ["type2"] =>
    array() {
        ["ticket1"] =>
        array(9) { 
           // ticket details here
        }
        ["ticket2"] =>
        array(10) { 
           // ticket details here
        }
        ["ticket3"] =>
        array(9) { 
           // ticket details here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

等等

我试图计算数组中的票证总数(二级项目的数量),但类型的数量是可变的,每个票证的字段数也是如此,所以我不能使用COUNT_RECURSIVE和数学来得到号码.

谁能帮我?

big*_*gkm 48

有点晚了,但这是一种干净的写作方式.

$totalTickets = array_sum(array_map("count", $tickets));
Run Code Online (Sandbox Code Playgroud)

假设$tickets是你的多维数组.

我已经扩展了代码以给出一个解释的例子,因为array_map可能对某些人来说是新的

$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
Run Code Online (Sandbox Code Playgroud)

因为我们不关心每种类型的中间结果,我们可以将结果提供给array_sum

$totalTickets = array_sum(array_map("count", $tickets));
Run Code Online (Sandbox Code Playgroud)


Swa*_*adq 24

$count = 0;
foreach ($array as $type) {
    $count+= count($type);
}
Run Code Online (Sandbox Code Playgroud)

  • @RoelVermeulen不,count($ type)是一个函数,而不是一个变量. (2认同)

Jac*_* M. 18

使用Count Recursive并减去First level count,如下所示:

count($mainArr, COUNT_RECURSIVE) - count($mainArr);
Run Code Online (Sandbox Code Playgroud)

如果你的数组有+3级别,只需添加[?]键:

count($mainArr[1], COUNT_RECURSIVE) - count($mainArr[1]);
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案!谢谢! (2认同)