PHP可变空外Foreach?

时间:2012-03-06 16:22:30

标签: php

我有一个类系统和一个函数,它可以从数据库结果中获取一个foreach。变量在foreach中分配,但在foreach之外它是空的。

// Top of file
private $movieList = array();

if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                // add each to the array
                $this->movieList[] = array('nid' => $row->nid, 'title' => $row->title, 'movie_pos_id' => $row->movie_pos_id);
                print_r($this->movieList); // variable full of stuff
            }
            // No results found
            return false;
        }

print_r($this->movieList); // variable empty

知道为什么吗?

2 个答案:

答案 0 :(得分:2)

在我看来,if语句之外的行永远不会执行,因为如果得到结果,你总是返回false。检查括号。你可能是这个意思:

if ($query->num_rows() > 0) {
    foreach ($query->result() as $row) {
        // add each to the array
        $this->movieList[] = 
            array('nid' => $row->nid, 'title' => $row->title, 
                'movie_pos_id' => $row->movie_pos_id);
        print_r($this->movieList); // variable full of stuff
    }
}
else {
    // No results found
    return false;
}

print_r($this->movieList);

答案 1 :(得分:1)

你的牙套不匹配。试试这个

// Top of file
private $movieList = array();

if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                // add each to the array
                $this->movieList[] = array('nid' => $row->nid, 'title' => $row->title, 'movie_pos_id' => $row->movie_pos_id);
                print_r($this->movieList); // variable full of stuff
            }
}else{
            // No results found
            return false;
}


print_r($this->movieList); // variable empty