Полный массив не возвращается PHP - PullRequest
0 голосов
/ 09 февраля 2012

Я пытаюсь создать класс twitter и создать объект, который вызывает методы и свойства этого класса. По сути, я делаю вызов базы данных для имен пользователей в твиттере и выполнение симплексных запросов с результатом. (Я опустил эту часть кода, потому что он работает нормально).

Кажется, все работает нормально, за исключением того, что я не могу понять, почему при return $this->posts возвращается только первый первый элемент массива. Когда я удаляю return, возвращается весь массив. Я проверяю это, используя print_r в объекте внизу.

   <?php 
    class twitter { 
        public $xml;
        public $count;
        public $query;
        public $result;
        public $city;
        public $subcategory;
        public $screen_name;
        public $posts;

        public function arrayTimeline(){
            $this->callDb($this->city, $this->subcategory);
            while($row = mysql_fetch_row($this->result)){ 
                foreach($row as $screen_name){ 
                    $this->getUserTimeline($screen_name, $count=2);
                }
                foreach($this->xml as $this->status){
                    return $this->posts[] = array("image"=>(string)$this->status->user->profile_image_url,"name"=>(string)$this->status->name, "username"=>(string)$this->status->user->name, "text"=>(string)$this->status->text, "time"=>strtotime($this->status->created_at)); 
                }
            }
        }


    $test = new twitter;
    $test->city="phoenix";
    $test->subcategory="computers";

    $test->arrayTimeline();

    print_r($test->posts);

    ?>

1 Ответ

5 голосов
/ 09 февраля 2012

Это потому, что return заставляет PHP покинуть метод, который вы в данный момент вызываете.Переместите возврат из циклов, и вы получите полный массив.

    public function arrayTimeline(){
        $this->callDb($this->city, $this->subcategory);
        while($row = mysql_fetch_row($this->result)){ 
            foreach($row as $screen_name){ 
                $this->getUserTimeline($screen_name, $count=2);
            }
            foreach($this->xml as $this->status){
                $this->posts[] = array("image"=>(string)$this->status->user->profile_image_url,"name"=>(string)$this->status->name, "username"=>(string)$this->status->user->name, "text"=>(string)$this->status->text, "time"=>strtotime($this->status->created_at)); 
            }
        }

        return $this->posts;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...