简体   繁体   English

PHP的while循环内foreach循环

[英]php while loop inside a foreach loop

Here this line $find_cond = str_replace('|',' ',$rem_exp); 这条线$find_cond = str_replace('|',' ',$rem_exp); returns 225 and 245 number. 返回225和245号。

I want to get the records based on these two id number. 我想基于这两个ID号获取记录。 But this below code returns the output repeatedly. 但是下面的这段代码反复返回输出。

How do I properly put the while loop code inside a foreach? 如何正确地将while循环代码放入foreach中?

foreach($arr_val as $key => $val)
{
    $c_subsubtopic = str_replace('-','_',$subsubtopic);
    $rem_exp = $val[$c_subsubtopic];
    $find_cond = str_replace('|',' ',$rem_exp);
    $sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id = '".$find_cond."' AND a.status = '1'";
    while($r = mysql_fetch_array(mysql_query($sql)))
    {
        echo $r['value_name'];
    }
}

The problem is that you are redoing the sql query at every iteration of the loop, thus resetting the results internal pointer, so you keep fetching the same array. 问题是您要在循环的每次迭代中重做sql查询,从而重置结果内部指针,因此您将继续获取同一数组。

$res = mysql_query($sql)

should be on it's own line before the while loop, and then 在while循环之前应该在它自己的行上,然后

while($r = msql_fetch_array($res))

This will properly increment through the $res list. 这将在$ res列表中正确增加。

Try this and you are done 试试这个,你就完成了

As you were getting may get multiple id in the string after replacing it so its better to use IN the where clause 由于替换后可能会在字符串中获得多个id,因此最好使用IN子句

foreach($arr_val as $key => $val)
{
    $c_subsubtopic = str_replace('-','_',$subsubtopic);
    $rem_exp = $val[$c_subsubtopic];
    $find_cond = str_replace('|',',',$rem_exp);
    $sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id IN('".$find_cond."') AND a.status = '1'";
    while($r = mysql_fetch_array(mysql_query($sql)))
    {
        echo $r['value_name'];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM