2012-02-09 90 views
0

我試圖創建一個twitter類並創建一個調用該類的方法和屬性的對象。基本上我正在做的是調用數據庫的Twitter用戶名和使用simplexml請求的結果。 (我省略了那部分代碼,因爲它工作正常)。完整數組未返回PHP

一切似乎工作正常,但我不明白爲什麼當我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); 

    ?> 

回答

5

這是因爲返回導致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; 
    }