这是我的代码。 例如。
<?php
$testing="70, 60, 60, 30";
$test=explode(",",$testing);
$total=$test[1]+$test[2]+$test[3];
echo $total-$test[0];
?>
现在我想要那种类型的函数,它自动添加数组的所有最后一个键,除了该数组的第一个键。最后,数组的所有最后一个键的总和从数组的第一个键中减去。 任何人都知道我是怎么做到的。
答案 0 :(得分:1)
如下所示: -
ExecuteQueryDynamic(@"DECLARE @Discontinued bit={0}; DECLARE @ProductID Int={1};
DECLARE @CategoryID Int={2};
SELECT DISTINCT * FROM Products
WHERE Discontinued = @Discontinued AND ProductId = @ProductID
AND CategoryID = @CategoryID;
", true, 5, 2).Dump();
输出: - https://eval.in/822897
答案 1 :(得分:1)
<?php
$total=0;
$testing="70, 60, 60, 30";
$test=explode(",",$testing);
for($i=0;$i<count($test);$i++){
if($i==0){}
else{$total +=$test[$i];}
}
echo $total-$test[0];
?>
答案 2 :(得分:1)
有许多方法可以使用单行代码(有时是两行)来实现这样一个简单的目标,它可以与输入数组中的任意数量的值一起使用:
// Extract the first value from the array
$first = array_shift($test);
// Subtract the first value from the sum of the rest
echo(array_sum($test) - $first);
// Change the sign of the first value in the array (turn addition to subtraction)
$test[0] = -$test[0];
// Add all values; the first one will be subtracted because we changed its sign
echo(array_sum($test));
// Sum all values, subtract the first one twice to compensate
echo(array_sum($test) - 2 * $test[0]));
// There is no second line; that's all
// Compute the sum of all but the first value, subtract the first value
echo(array_sum(array_chunk($test, 1)) - $test[0]);
// There is no second line; two function calls are already too much
留给读者练习。
有用的阅读:PHP array functions的文档。
答案 3 :(得分:0)
希望这会有所帮助。
<?php
$testing="70, 60, 60, 30";
$test=explode(",",$testing);
$total=0;
foreach ($test as $key =>$value) {
if($key === 0) {
$total = $total - $value;
} else {
$total = $total + $value;
}
}
echo $total;
?>