我写了这段代码:
$final = array(
($data[0] - $data[1]),
($data[1] - $data[2]),
($data[2] - $data[3]),
($data[3] - $data[4]),
($data[4] - $data[5]),
($data[5] - $data[6])
);
其中一些会返回负数(-13
,-42
等...),如何将否定数字更改为0
?
顺便说一下,我的想法是:
$data_string = join(",", $final);
示例:我需要转换它,如下所示:
1,3,-14,53,23,-15 => 1,3,0,53,23,0
答案 0 :(得分:6)
您可以映射:
$zeroed = array_map(function($v) {return max(0, $v);}, $final);
将所有数字设置为低于0。
此外,您可以使用$data
:
$final = array_reduce($data, function($v, $w)
{
static $last;
if (null !== $last) $v[] = max(0, $last - $w);
$last = $w;
return $v;
}, array());
$data_string = join(",", $final);
请参阅array_reduce
。
编辑:foreach循环可能更容易理解,我也添加了一些评论:
// go through all values of data and substract them from each other,
// negative values turned into 0:
$last = NULL; // at first, we don't have a value
$final = array(); // the final array starts empty
foreach($data as $current)
{
$isFirst = $last === NULL; // is this the first value?
$notFirst = !$isFirst;
if ($notFirst)
{
$substraction = $last - $current;
$zeroed = max(0, $substraction);
$final[] = $zeroed;
}
$last = $current; // set last value
}
这是demo。
答案 1 :(得分:2)
我猜这是功课。如果是这样,请将其标记为。
提示:
答案 2 :(得分:1)
我喜欢Hakre的紧凑答案。但是,如果您有更复杂的要求,则可以使用以下函数:
<?php
$data = array(11,54,25,6,234,9,1);
function getZeroResult($one, $two) {
$result = $one - $two;
$result = $result < 0 ? 0 : $result;
return $result;
}
$final = array(
getZeroResult($data[0], $data[1]),
getZeroResult($data[1], $data[2]),
getZeroResult($data[2], $data[3]),
getZeroResult($data[3], $data[4]),
getZeroResult($data[4], $data[5]),
getZeroResult($data[5], $data[6])
);
print_r($final);
?>
http://codepad.org/viGBYj4f(echo
在测试前显示$result
。)
这给了你:
Array
(
[0] => 0
[1] => 29
[2] => 19
[3] => 0
[4] => 225
[5] => 8
)
注意,你也可以退回三元:
function getZeroResult($one, $two) {
$result = $one - $two;
return $result < 0 ? 0 : $result;
}
以及在循环中使用它:
<?php
$data = array(11,54,25,6,234,9,1);
function getZeroResult($one, $two) {
$result = $one - $two;
echo "$one - $two = $result\n";
return $result < 0 ? 0 : $result;
}
$c_data = count($data)-1;
$final = array();
for ($i = 0; $i < $c_data; $i++) {
$final[] = getZeroResult($data[$i], $data[$i+1]);
}
print_r($final);
?>