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.
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