我正在尝试创建一个twitter类并创建一个调用该类的方法和属性的对象。基本上我正在做的是为twitter用户名调用数据库并使用结果生成simplexml请求。 (我省略了代码的那部分,因为它工作正常)。
一切似乎都运转正常,但我无法弄清楚为什么当我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);
?>
答案 0 :(得分:5)
这是因为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;
}