这是我的数组输出:
array:2 [
0 => array:1 [
"medium " => " 1"
]
1 => array:1 [
" small " => " 2"
]
]
我的解决方案
$sumVariant = array();
foreach ($data as $key => $value) {
foreach ($value as $k => $v) {
//dd(trim($v));
$sumVariant += trim($v);
}
}
dd($sumVariant);
如何计算返回3的medium
和small
的总数?谢谢!
答案 0 :(得分:1)
我在你的问题中写下你的代码。并进行如下修改。它给你正确的答案。
<?php
$data =array(0=>array("medium "=>" 1"),1=>array(" small "=>" 2"));
$sumVariant=0;
foreach ($data as $key => $value) {
foreach ($value as $k => $v) {
//dd(trim($v));
$sumVariant += trim($v);
}
}
echo $sumVariant;?>
答案 1 :(得分:0)
<?php
$total = 0;
foreach ($array as $inputArray) {
if (array_key_exists ("medium", $array)) $total += $array["medium"] ;
if (array_key_exists ("small", $array)) $total += $array["small"] ;
}
答案 2 :(得分:0)
使用array_walk_recurive
$array_total = 0;
$arr = array(array('small'=>2), array('medium'=>1));
array_walk_recursive($arr, function($value, $key){
global $array_total;
$array_total += $value;
});
echo $array_total; // output 3
答案 3 :(得分:0)
$data =array(0=>array("medium "=>" 1"),1=>array(" small "=>" 2"));
foreach ($data as $array_single) {
$sum_value += array_sum($array_single);
}
echo $sum_value;
array_sum()返回整数之和表示为字符串或int
examle :: -
<?php
$a=array(' 5',15,25,'ajj');
echo array_sum($a);
?>
O / P :: - 45