确定数组是否具有负数并将其更改为零 [英] Determine if the array has negative numbers and change them to zero
本文介绍了确定数组是否具有负数并将其更改为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了这段代码:
$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
?
Some of them will return negative numbers (-13
,-42
etc...), how to change the negative ones to 0
?
按照我想的方式做的是:
By the way the think i do after is:
$data_string = join(",", $final);
示例:我需要将其转换如下:
Example: I need to convert it like in the following:
1,3,-14,53,23,-15 => 1,3,0,53,23,0
推荐答案
我喜欢Hakre的简洁答案.但是,如果您有更复杂的要求,则可以使用以下函数:
I like Hakre's compact answer. However, if you have a more complex requirement, you can use a function:
<?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
)
注意,您也可以只返回三元:
Note, you could also just return the ternary:
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);
?>
这篇关于确定数组是否具有负数并将其更改为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文