【问题标题】:Php while and for loop issuePHP while 和 for 循环问题
【发布时间】:2013-07-25 05:13:41
【问题描述】:

我在while循环中有问题..我的问题在下面描述。

$sql = mysql_query($query, $this->db);
        if(mysql_num_rows($sql) > 0)
        {
            $result = array();
            while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC))
            {

                $theature = explode(",",$rlt['mw_movie_theature']);
                //echo 'count'.count($theature).'<br/>'; print_r($theature);

                for($i = 0; $i<count($theature); $i++ )
                {
                    $sqls = mysql_query("SELECT * FROM mw_theatres WHERE status = 1 AND id='".$theature[$i]."'", $this->db);
                    $rlts = array();
                    while($rlts = mysql_fetch_array($sqls,MYSQL_ASSOC))
                    {
                        $rlt['movie'] = $rlts;
                    }
                }
                $rlt['value'] = 'true';
                $result[] = $rlt;

            }

            echo '<pre>';print_r($result);die;

$theature 变量有 2,3,4 个值。但 $rlt['movie'] 的值仅给出最后 4 个 id 结果。我想要 2,3,4 个 id 值。

【问题讨论】:

  • 你应该标记正确的答案或添加你自己的..

标签: php for-loop while-loop


【解决方案1】:

你应该试试这个:--

$sqls = mysql_query("SELECT * FROM mw_theatres WHERE status = 1 AND id='".$theature[$i]."'", $this->db);
$rlts = array();
$j=0;
while($rlts = mysql_fetch_array($sqls,MYSQL_ASSOC))
{
     $rlt['movie'][$j] = $rlts;
     $j++;
}

【讨论】:

    【解决方案2】:

    因为每次你将 $rlts 赋给同一个变量 $rlt['movie']。试试 $rlt['movie'][]

    【讨论】:

      【解决方案3】:

      不要使用explode方法你正在使用额外的循环你可以解决这个查询并像这样在while循环中得到结果

      $sqls = mysql_query("SELECT * FROM mw_theatres WHERE status = 1 AND id IN (".$theature.")", $this->db);
      $rlts = array();
      $k = 0;
      while($rlts = mysql_fetch_array($sqls,MYSQL_ASSOC))
      {
          $rlt['movie'][$k] = $rlts;
          $k++;
      }
      

      在 where clase 中,我们使用 id IN,它仅从作为字符串的变量中的 id 检查,因此没有使用额外的 for 循环和 explod 函数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-05
        • 1970-01-01
        • 1970-01-01
        • 2011-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-11
        相关资源
        最近更新 更多