所以我对每个循环都有一些,并且我试图在最后回显$ sql的值。我实际上是在PDO中使用它,但回声显示了这个问题。
$values = "1,2";
$values = explode(',',$values);
$set1 = "2,4";
$set1 = explode(',',$set1);
$set2 = "3,2";
$set2 = explode(',',$set2);
foreach($set1 as $set1val){
if ($set1val==2) {
$sql = "sql one runs";//should run on 1st iteration since 2 will equal 2
echo 'hi';//should echo on 1st iteration since 2 will equal 2
}
}
foreach($set2 as $set2val){
if ($set2val==2) {
$sql = "sql two runs";//should run on 2nd iteration since 2 will equal 2
echo 'bye';//should echo on 2nd iteration since 2 will equal 2
}
}
foreach($values as $value){
echo $sql;
$stmt = $db->query($sql);
}
//The Result Output
'hi' 'bye' 'sql two runs' 'sql two runs' <-- doesn't echo 'sql one runs'
//The Output Required
'hi' 'bye' 'sql one runs' 'sql two runs' <-- Works great, but not outputting this
如何输出所需的输出?知道如何做到这一点,以便正确的声明回显/运行?
答案 0 :(得分:2)
它永远不会回显sql one runs
,因为第二个foreach
会用sql two runs
覆盖它。如果需要在脚本末尾保存sql字符串,可以将它们存储在数组中。很难指定如何不清楚$values
与SQL的关系,即哪个SQL应与哪个$value
一起运行。
答案 1 :(得分:0)
问题是,您首先将sql one runs
保存在$sql
中,但您使用$sql
做的下一件事是保存sql two runs
,覆盖之前的值。因此,您需要将这些值保存在数组中,并修改最后一个foreach
。像这样:
foreach($set1 as $set1val){
if ($set1val==2) {
$sql[0] = "sql one runs";//should run on 1st iteration since 2 will equal 2
echo 'hi';//should echo on 1st iteration since 2 will equal 2
}
}
foreach($set2 as $set2val){
if ($set2val==2) {
$sql[1] = "sql two runs";//should run on 2nd iteration since 2 will equal 2
echo 'bye';//should echo on 2nd iteration since 2 will equal 2
}
}
foreach($sql as $value){
echo $value;
$stmt = $db->query($value);
}