dourang6858 2018-04-17 06:14
浏览 95
已采纳

string_replace在循环中替换第一个段

This question is based on my previous question. This is my code.

$this->logger->debug($datauser);   // [ZN1961] => Array([#A] => 12 >  4 [#B] => 12 >  2 ), [ZN1962] => Array ([#A] => 20 >  4 [#B] => 20  >  2 )
logicexpression = ((#A) OR (#B) );

$newArr = array();
foreach ($datauser as $key => $value) {
    foreach ($value as $logname => $cond) {
        $this->logger->debug($cond);     /// WHEN DEBEG HERE it gives correctly the $cond in each iteration          
        $logicexpression =str_replace($logname, $cond, $logicexpression);
    }
$this->logger->debug($logicexpression ); // here I am always getting (12 >  4) OR (12 >  2)
    }
`

So my problem is as I mentioned in the code I am always getting (12 > 4) OR (12 > 2).
So the output is,

@547,12 >  4
@547, 12 >  2
@557, (12 >  4) OR (12 >  2)
@547, 20 >  4
@547, 20 >  2
@557, (12 >  4) OR (12 >  2) // here it should has to come as (20 >  4) OR (20 >  2)`

Even I am getting $cond correctly while debugging couldn't replace the relevant $cond in iteration. I couldn't understand why ? please help me.

  • 写回答

1条回答 默认 最新

  • drn5375 2018-04-17 06:26
    关注

    You have to define a new variable $newlogicexpression inside the iteration, otherwise after the first iteration you don't have (#A) OR (#B) in $logicexpression anymore and the replace won't work...

    $logicexpression = ((#A) OR (#B) );
    foreach ($datauser as $key => $value) {
        $newlogicexpression = $logicexpression;
        foreach ($value as $logname => $cond) {
            $newlogicexpression = str_replace($logname, $cond, $newlogicexpression);
        }
        $this->logger->debug($newlogicexpression);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?