在 PHP 中添加数组值的问题
Problem with addition of array values in PHP
我在对象数组中有一些数据,我需要对存储在 $data['gross'].
中的值求和
$data = [
[
"title" => "The World's End",
"genre" => "Sci-fi",
"year" => 2013,
"gross" => 26004851
],
[
"title" => "Scott Pilgrim vs. the World",
"genre" => "Sadness",
"year" => 2010,
"gross" => 31524275
]
];
我用循环试过这个:
for ($i = 0; $i <= (count($data)-1); $i++) {
foreach ($data[$i] as $id => $row) {
$sum = 0;
if ($id == "gross") {
$sum += $row;
}
echo $sum;
}
}
但不是将它们相加,而是将数字连接为字符串。为什么?我试图回应这个变量的类型,但它始终是一个整数。请问是哪里出了问题?
一行代码即可实现:
$data = [
[
"title" => "The World's End",
"genre" => "Sci-fi",
"year" => 2013,
"gross" => 26004851
],
[
"title" => "Scott Pilgrim vs. the World",
"genre" => "Sadness",
"year" => 2010,
"gross" => 31524275
]
];
$sum = array_sum(array_column($data,'gross'));
echo $sum;
使用此输入 $sum
将是 57529126
我在对象数组中有一些数据,我需要对存储在 $data['gross'].
中的值求和$data = [
[
"title" => "The World's End",
"genre" => "Sci-fi",
"year" => 2013,
"gross" => 26004851
],
[
"title" => "Scott Pilgrim vs. the World",
"genre" => "Sadness",
"year" => 2010,
"gross" => 31524275
]
];
我用循环试过这个:
for ($i = 0; $i <= (count($data)-1); $i++) {
foreach ($data[$i] as $id => $row) {
$sum = 0;
if ($id == "gross") {
$sum += $row;
}
echo $sum;
}
}
但不是将它们相加,而是将数字连接为字符串。为什么?我试图回应这个变量的类型,但它始终是一个整数。请问是哪里出了问题?
一行代码即可实现:
$data = [
[
"title" => "The World's End",
"genre" => "Sci-fi",
"year" => 2013,
"gross" => 26004851
],
[
"title" => "Scott Pilgrim vs. the World",
"genre" => "Sadness",
"year" => 2010,
"gross" => 31524275
]
];
$sum = array_sum(array_column($data,'gross'));
echo $sum;
使用此输入 $sum
将是 57529126