3
$array[0] = 100;
$array[1] = 10;
$array[2] = 15;

我怎样才能通过它的键得到数组的总和,就像key = (0,1)这样sum = 110

4

8 回答 8

3
$sum = array_sum(
    array_intersect_key($array, array_flip([0,1])
);

没有测试它,但应该可以工作:)

于 2013-01-07T12:21:10.203 回答
3

尝试:

$array = array(
  0 => 100,
  1 => 10,
  2 => 15
);
$keys  = array(0, 1);
$sum   = 0;

foreach ( $keys as $key ) {
  $sum += $array[$key];
}
于 2013-01-07T12:16:50.387 回答
3

最好和最简单的方法是

$result = array_sum($your_array);
于 2013-01-07T12:19:11.207 回答
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)

参考:

array_intersect_key

数组翻转

于 2015-02-24T19:23:25.023 回答
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);
于 2013-01-07T12:27:15.590 回答
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;
于 2013-12-11T04:48:50.203 回答
-1

如果您想对初始两个键求和,请使用以下代码:

array_sum(array_slice($array,0,2)); // will return 110

参考:

array_sum

array_slice

于 2013-01-07T12:17:52.583 回答
-2
$count = 0;
for($i=0;$i<count($array);$i++){
 $count = $count + $array[$i];
}

echo $count;
于 2013-01-07T12:16:29.163 回答