简体   繁体   中英

php while loop inside a foreach loop

Here this line $find_cond = str_replace('|',' ',$rem_exp); returns 225 and 245 number.

I want to get the records based on these two id number. But this below code returns the output repeatedly.

How do I properly put the while loop code inside a 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.

$res = mysql_query($sql)

should be on it's own line before the while loop, and then

while($r = msql_fetch_array($res))

This will properly increment through the $res list.

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

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'];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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