如何修复此php以包含数组的完整列表?

时间:2014-08-26 01:07:46

标签: php mysql variables for-loop

$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
    while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
   for ($i = 1; $i < count($array); ++$i) {
        $userids = $array[$i].',';

 $q2 = mysql_query("SELECT * FROM item WHERE approved = 1 AND id IN(".$userids."0)");  
echo $userids;
//NOTE: my echo is spitting out "18622,44968,44968," but when using $userids in mysql query it doesn't include the full list of numbers
            }   
        }

我在mysql查询之后放置}以尝试在for循环中包含变量,如果我在查询之前关闭括号$ userids只打印数组中的最后一个数字。

1 个答案:

答案 0 :(得分:0)

在查询之前关闭括号并使用连接而不是在每次迭代时重新分配$userids

$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
while($row = mysql_fetch_array($q)) {
    $array = (explode(":",$row['recent_views']));
    for ($i = 1; $i < count($array); ++$i) {
        $userids .= $array[$i].',';
              // ^ missing the period here
    }
}

$q2 = mysql_query("SELECT * FROM item LEFT JOIN subcategory
ON item.subcategory_id=subcategory.subcategory_id LEFT JOIN genre ON item.genre_id=genre.genre_id WHERE approved = 1 AND broken = 0 AND id IN(".$userids."0)");  
echo $userids;

你也可以摆脱for循环并使用implode()

while($row = mysql_fetch_array($q)) {
    $array = (explode(":",$row['recent_views']));
    $userids .= implode(',', $array) + ',';
}

虽然这可以解决问题,但要知道这不是非常有效也不可维护。使用SQL JOIN语法将用户的最近视图与子类别组合在一个查询中会更有意义。