array() { ["ticket1"] => array(9) { -6ren">
gpt4 book ai didi

php - PHP 中的多维数组计数

转载 作者:IT王子 更新时间:2023-10-29 00:13:44 24 4
gpt4 key购买 nike

我有一个多维数组设置如下

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
}
}
}

等等

我正在尝试计算数组中票的总数(二级项目的数量),但是类型的数量是可变的,每张票的字段数量也是可变的,所以我不能使用 COUNT_RECURSIVE和数学来得到这个数字。

谁能帮帮我?

最佳答案

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

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

假设 $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

因为我们不关心每种类型的中间结果,所以我们可以将结果输入 array_sum

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

关于php - PHP 中的多维数组计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9062770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com