douju1852 2017-12-01 15:32
浏览 84
已采纳

Foreach循环使用多个str_replace

I have a foreach loop in a PHP script that outputs icons / links from a database. I've used this question to use str_replace to change some values after the icons are rendered.

foreach ($icons as $ic)
    { echo str_replace('{{EMP_NO}}', $_SESSION['EmpNo'], $ic['url']) . ' '; }

I need to do a similar operation on a value {{FIRST_NAME}} but when I append with a second str_replace the second command / value is ignored. Like this:

foreach ($icons as $ic)

    { echo str_replace('{{EMP_NO}}', $_SESSION['EmpNo'], $ic['url']) . ' '; }
    { echo str_replace('{{FIRST_NAME}}', $_SESSION['FirstName'], $ic['url']) . ' '; }

When I try to combine them like this it doubles the icons output which I don't want:

foreach ($icons as $ic) { echo str_replace('{{EMP_NO}}', $_SESSION['EmpNo'], $ic['url']) . ' '; echo str_replace('{{FIRST_NAME}}', $_SESSION['FirstName'], $ic['url']) . ' '; }

How do I also str_replace {{FIRST_NAME}}?

  • 写回答

2条回答 默认 最新

  • 普通网友 2017-12-01 15:36
    关注

    str_replace can replace array of values to array of other values:

    foreach ($icons as $ic) {
        echo str_replace(
            array('{{EMP_NO}}', '{{FIRST_NAME}}'),
            array($_SESSION['EmpNo'], $_SESSION['FirstName']), 
            $ic['url']) . ' '
        );
    }
    

    And as already mentioned in @David's answer, though your code has a correct syntax, but its' logic is flawed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?