如何从键中获取数组元素的值
How to get values of array element from key
以下是我的数组
Array(
[id] => 1
[user_id] => 30
[list] => Array
(
[0] => Array
(
[id] => 1
[card_id] => 6
[amount] => 400
)
[1] => Array
(
[id] => 2
[card_id] => 3
[amount] => 500
)
)
)
我想从上面的数组中获取 amount 键的值,它位于 list 键中。
我想将该值存储在一个变量中。
P.S :在 list 数组中它将有多个数组
编辑:
输出中应该有所有金额的总和。
例如,上面的数组总和将是 900
是 $total_amount = 900
这是你想要的,简单的foreach:
$array = [
"id" => 1,
"user_id" => 30,
"list" => [
[
"id" => 1,
"card_id" => 6,
"amount" => 400,
],
[
"id" => 2,
"card_id" => 3,
"amount" => 500,
]
]
];
$totalAmount = 0;
foreach ($array["list"] as $array){
$totalAmount += $array["amount"];
}
var_dump($totalAmount);
结果:900
一个衬垫 array_column and array_sum;
echo array_sum(array_column($array["list"], 'amount')); // 900
以下是我的数组
Array(
[id] => 1
[user_id] => 30
[list] => Array
(
[0] => Array
(
[id] => 1
[card_id] => 6
[amount] => 400
)
[1] => Array
(
[id] => 2
[card_id] => 3
[amount] => 500
)
)
)
我想从上面的数组中获取 amount 键的值,它位于 list 键中。 我想将该值存储在一个变量中。 P.S :在 list 数组中它将有多个数组
编辑:
输出中应该有所有金额的总和。
例如,上面的数组总和将是 900
是 $total_amount = 900
这是你想要的,简单的foreach:
$array = [
"id" => 1,
"user_id" => 30,
"list" => [
[
"id" => 1,
"card_id" => 6,
"amount" => 400,
],
[
"id" => 2,
"card_id" => 3,
"amount" => 500,
]
]
];
$totalAmount = 0;
foreach ($array["list"] as $array){
$totalAmount += $array["amount"];
}
var_dump($totalAmount);
结果:900
一个衬垫 array_column and array_sum;
echo array_sum(array_column($array["list"], 'amount')); // 900