dongluan2612 2017-07-31 20:41
浏览 30
已采纳

我如何在这里正确使用str_replace?

I'm trying to take data in a HTML table column and format it with PHP depending on it's value. The column tracks movement, so if it's a positive value I'd like to add an upward facing arrow (↑) before the value. If it's a negative number, I'd like to replace the '-' with a downward facing arrow (↓). I've set up an IF/ELSE statement that checks the value of the data. I can get the upward arrow to show up without issue, but I'm having trouble formatting negative values the way I'd like. I've researched the issue on Stack and started using str_replace. The way I have it set up now, I can get a negative value like -2 to be replaced with ↓2, but right next to the ↓2 the -2 remains (like this ↓2 -2). I somewhat understand why this is happening, I just don't know how to get it to do what I want. Here is my IF statement:

if ($row['move'] > 0) {
    $arrow = '↑ ';
} else if ($row['move'] < 0) {
    $arrow = str_replace('-', '&#8595; ', $row['move']);
} else {
    $arrow = '';
}

And here is how I print my data (some of it, to avoid irrelevant code). $style changes the color of the text:

echo "<td{$style}>" . $arrow.$row["move"] . "</td><td>"

Thank you for whatever help you can offer!

  • 写回答

1条回答 默认 最新

  • duanji9378 2017-07-31 20:46
    关注

    I wouldn't use str_replace, in fact, but instead take the absolute value of $row['move'].

    // decide which arrow to use
    if ($row['move'] > 0) {
        $arrow = '&#8593; ';
    } else if ($row['move'] < 0) {
        $arrow = '&#8595; ';
    } else {
        $arrow = '';
    }
    
    // remove the sign (if it's there)
    $move = abs($row['move']);
    
    // output
    echo "<td{$style}>{$arrow}{$move}</td><td>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 创建一个数据库(要创建的表和记事本的代码截图))
  • ¥15 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败
  • ¥15 用Ros中的Topic通讯方式控制小乌龟的速度,走矩形;编写订阅器代码
  • ¥15 LLM accuracy检测
  • ¥15 pycharm添加远程解释器报错
  • ¥15 如何让子窗口鼠标滚动独立,不要传递消息给主窗口