$array[0] = 100;
$array[1] = 10;
$array[2] = 15;
我怎样才能通过它的键得到数组的总和,就像key = (0,1)
这样sum = 110
?
$sum = array_sum(
array_intersect_key($array, array_flip([0,1])
);
没有测试它,但应该可以工作:)
尝试:
$array = array(
0 => 100,
1 => 10,
2 => 15
);
$keys = array(0, 1);
$sum = 0;
foreach ( $keys as $key ) {
$sum += $array[$key];
}
最好和最简单的方法是
$result = array_sum($your_array);
这是我通过定义的键对数组求和的解决方案:
$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)
参考:
$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);
尝试这个
$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;
如果您想对初始两个键求和,请使用以下代码:
array_sum(array_slice($array,0,2)); // will return 110
参考:
$count = 0;
for($i=0;$i<count($array);$i++){
$count = $count + $array[$i];
}
echo $count;