user732027
user732027

Reputation: 99

Full Array not Returned PHP

I'm trying to create a twitter class and create an object that calls the methods and properties of that class. Essentially what I'm doing is calling the database for twitter usernames and making simplexml requests with the result. (I've omitted that portion of the code because it's working fine).

Everything seems to be working alright, except I cannot figure out why when I return $this->posts only the first the first item of the array is returned. When I remove the return the entire array is returned. I'm testing it by using print_r in the object at the bottom.

   <?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);

    ?>

Upvotes: 0

Views: 345

Answers (1)

Dan
Dan

Reputation: 1888

This is because return causes PHP to leave the method you are currently calling. Move the return out of the loops and you will get the full array.

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

Upvotes: 5

Related Questions