0

I want to replace several strings in an iteration pattern.

foreach (self::model()->findAll($q) as $ruleSet) {
$stringSet =$ruleSet->logic;   // It gives as "1 AND 2"
$dataset = array ();            

foreach (CampaignAutoLogic::model()->findAll($q) as $rule) {
    $operator = $rule->operator;
    $value = $rule->value;

    $condition = sprintf(5, $operator , $value);  // 5>3 (firs_iter), 5<0

    $w= str_replace($rule->id, $condition, $stringSet);  // $rule->id first loop gives the value as 1 , second loop the value is 2 
    $stringSet=$w;                  

                }                       

            }
$this->logger->debug($stringSet);

If I am execute the above code It is not giving as (5>3 AND 5<0). I know I have to take the all $condition out and have replace the $stringSet at once. But don't know how to do them. help me

Shiromi
  • 159
  • 1
  • 9
  • What is `sprintf(5, $operator , $value);` supposed to do? – brombeer Apr 04 '18 at 06:48
  • I think sprintf is used for replace the % sign with specified variable. – itsme Apr 04 '18 at 06:49
  • It's generating the condition. for first 5 > (the particular operator coming from db) 3 (the particular valuecoming from db). Simply replacing.. – Shiromi Apr 04 '18 at 06:50
  • Can you provide an [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)? We don't know what half your copied code does and how it interacts with the problem. – xander Apr 04 '18 at 06:51
  • `sprintf()` expects the first parameter to be a format - http://php.net/manual/en/function.sprintf.php – Nigel Ren Apr 04 '18 at 06:51

1 Answers1

1

The problem is that your sprintf() needs a format paramter to say how to present the data. So if you change that line to...

$condition = sprintf("%d%s%d", 5, $operator , $value);  // 5>3 (firs_iter), 5<0

This says to output the string as a number a string and another number. You should get the output your after.

There is another problem though, if you had conditions with logic="1 AND 2" and rules "5>2 (first_iter), 5<0", when you come to replace the second rule you will get "5>5<0 AND 5<0" as this has replaced the number 2 from the first rule as well as the 2 in the main logic.

You may be better off having logic which has (for example) "#1 AND #2" and then your replace becomes...

$w= str_replace("#".$rule->id, $condition, $stringSet);  // $rule->id first loop gives the value as #1 , second loop the value is #2
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Thanks for the help. Due to your idea I have sort out the problem. – Shiromi Apr 04 '18 at 08:39
  • If this has helped, please consider marking it as answered. https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Nigel Ren Apr 04 '18 at 09:35