如果负值打印“0”代替

If a negative value print "0" instead

我有一个简单的 php 脚本将 csv 文件转换为不同的布局,效果很好,但我想添加一条规则,如果值为负,则输出 0。 有人能给我指明正确的方向吗(下面的代码标记了要应用的规则)

谢谢

<?php

function twoDecs($num_in)
{
    $split = explode('.', $num_in);
    if(!isset($split[1]))
        $num_out = $num_in . '.00';
    else{
        if(strlen($split[1])<2)
            $num_out = $split[0] . '.' . $split[1] . '0';
        else
            $num_out = $split[0] . '.' . $split[1];
    }

    return $num_out;
}

function array_to_csv($array_in)
{
    $csv_content = 'sku;qty;special_price;price;is_in_stock
';
    $lines = explode('
', $array_in);

    for($i=0;$i<count($lines);$i++)
    {
        $line = explode(',', $lines[$i]);
        if(trim($line[1])!='')
        {
            $csv_content .= trim($line[1]) . ';';
            $csv_content .= trim($line[8]) . ';';  <----- line where rule to be added
            $csv_content .= twoDecs(trim($line[6])) . ';';
            $csv_content .= twoDecs(trim($line[7])) . ';';
            $csv_content .= '1' . '
';
        }
        unset($line);
    }

    $now = date('YmdHis');
    file_put_contents('files/ProductUpdateRF.csv', $csv_content);
    echo '<a href="files/ProductUpdateRF.csv"> Download reformatted CSV here. </a>';
}
?>

试用:

$csv_content .= (intval(trim($line[8])) < 0 ? "0" : trim($line[8])) . ';';

这使用 ternary operator,它是 shorthand if()

为了保持代码的可读性并解决您的问题,您可以使用 ternary (shorthand) operator ?:

$csv_content .= (float) $line[8] < 0 ? 0 : trim($line[8]) . ';';

给你:

$csv_content .= max(trim($line[8]), 0).';';  

这使用 Max,其中 return 是最高值。在这种情况下,如果第一个参数的值小于零(第二个参数),则 MAX 将 return 为零

if ($line[8]<0)
    $csv_content .= 0 ';'; 
else 
    $csv_content .= trim($line[8]) . ';';