确定数组是否具有负数并将其更改为零

Ric*_*rdo 0 php arrays

我写了这段代码:

$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]) 
);
Run Code Online (Sandbox Code Playgroud)

他们中有些人将返回负数(-13,-42等...),如何改变消极的到0

顺便说一下,我想做的事情是:

$data_string = join(",", $final);
Run Code Online (Sandbox Code Playgroud)

示例:我需要转换它,如下所示:

1,3,-14,53,23,-15 => 1,3,0,53,23,0
Run Code Online (Sandbox Code Playgroud)

hak*_*kre 6

你可以映射:

$zeroed = array_map(function($v) {return max(0, $v);}, $final);
Run Code Online (Sandbox Code Playgroud)

将所有数字设置为低于0到0.

array_mapmax.

此外,您可以使用$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);
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

这是演示.