我不知道这是否可能。我有一个数组(‘2’,'4','9','16'),我想得到(2-4),和(4-9)和(9-16)的值。每一个减去下一个数字,你有什么办法做到这一点吗?谢谢。
发布于 2016-01-28 22:04:14
<?php
$array=array('2','4','9','16');
foreach( $array as $k=> $v){
if($v !=end($array)){
echo $v-$array[$k+1]."\n";
}
}
更新以排除16-0
发布于 2016-01-28 22:07:04
当然是的。例如:
$array = array(2, 4, 9, 16);
$output = array();
foreach ($array as $key => $number) {
if (isset($array[$key+1])) {
$output[$number] = $number - $array[$key+1];
}
}
var_dump($output);
然后,$output
数组如下所示:
array(3) {
[2]=>
int(-2)
[4]=>
int(-5)
[9]=>
int(-7)
}
请注意,最后一个数字没有条目,因为您可以自然地不从其中减去下一个数字,因为没有。
发布于 2016-01-28 23:11:33
另一种记录方法:
$test_array = array(1,5,12,24,79);
$new_array = array();
$array_length = sizeof($test_array);
for($n = 1; $n <= ($array_length - 1); $n++)
{
// Get the current value
$x = current($test_array);
// Move the internal pointer
next($test_array);
// Get the next value
$y = current($test_array);
// Calculate the result in the new array
$new_array[] = $x-$y;
}
https://stackoverflow.com/questions/35072785
复制相似问题