$array[0] = 100;
$array[1] = 10;
$array[2] = 15;
如何通过key = (0,1)
之类的键获取数组的总和,以便sum = 110
?
答案 0 :(得分:3)
尝试:
$array = array(
0 => 100,
1 => 10,
2 => 15
);
$keys = array(0, 1);
$sum = 0;
foreach ( $keys as $key ) {
$sum += $array[$key];
}
答案 1 :(得分:3)
最简单的方法是
$result = array_sum($your_array);
答案 2 :(得分:3)
$sum = array_sum(
array_intersect_key($array, array_flip([0,1])
);
没有测试,但应该工作:)
答案 3 :(得分:0)
$array[0] = 100;
$array[1] = 10;
$array[2] = 15;
$sum = function($keys = array(),$arrayList= array()) {
$s = 0;
foreach ($arrayList as $key => $value) {
if(in_array($key, $keys)) {
$s+= $value;
}
}
echo $s;
};
$sum(array(0,1),$array);
答案 4 :(得分:0)
试试这个
$array[0] = 100;
$array[1] = 10;
$array[2] = 15;
echo array_sum($array);
或试试这个
$array[0] = 100;
$array[1] = 10;
$array[2] = 15;
$sum=0;
foreach (range(0,1) as $key)
{
$sum = $sum+$array[$key];
}
echo $sum;
答案 5 :(得分:0)
这是我通过定义键对数组进行求和的解决方案:
$myArray=Array("Array Title","1000",2000,3000}; // array example with stings and integers
var_dump(array_intersect_key($myArray, array_flip(Array(1,2)))); // int(3000)
var_dump($myArray); // int(6000)
参考文献:
答案 6 :(得分:-1)
如果你想要初始两个键,那么使用下面的代码:
array_sum(array_slice($array,0,2)); // will return 110
参考文献:
答案 7 :(得分:-2)
$count = 0;
for($i=0;$i<count($array);$i++){
$count = $count + $array[$i];
}
echo $count;