【问题标题】:php while loop inside a foreach loopphp while循环在foreach循环中
【发布时间】:2014-10-19 19:26:28
【问题描述】:

这行$find_cond = str_replace('|',' ',$rem_exp); 返回 225 和 245 数字。

我想根据这两个 id 号获取记录。但是下面的代码重复返回输出。

如何正确地将 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'];
    }
}

【问题讨论】:

  • 建议先打印$sql,运行sql查看结果。
  • 就像他说的。首先提取您的数据集。然后针对它运行你的 while 语句。

标签: php mysql arrays foreach while-loop


【解决方案1】:

问题是您在循环的每次迭代中都重做 sql 查询,因此重置了结果内部指针,因此您继续获取相同的数组。

$res = mysql_query($sql)

应该在while循环之前单独一行,然后

while($r = msql_fetch_array($res))

这将在 $res 列表中正确递增。

【讨论】:

    【解决方案2】:

    试试这个,你就完成了

    正如你得到的那样,替换后可能会在字符串中获得多个 id,因此最好使用 IN the where 子句

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

    【讨论】:

    • @Beginner 你能把你在 $subsubtopic 中得到的东西贴出来吗?
    • 您在什么基础上使用 IN 而不是 = ?
    • @RamSharma 这只是一个假设,因为输出重复了,然后我问他变量中的值
    • @Veerendra,请。不要假设。让用户解释他的问题。
    • @Veerendra :在我的 $subsubtopic 中,我得到了引擎描述。 engine_description 是我的列名。所以,我正在使用 str_replace
    猜你喜欢
    • 1970-01-01
    • 2015-07-03
    • 2017-05-28
    • 2012-10-02
    • 2013-10-01
    • 2016-11-27
    • 1970-01-01
    • 2018-02-09
    • 2018-05-20
    相关资源
    最近更新 更多