【问题标题】:Full Array not Returned PHP未返回完整数组 PHP
【发布时间】:2012-02-09 07:42:21
【问题描述】:

我正在尝试创建一个 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);

    ?>

【问题讨论】:

    标签: php arrays oop


    【解决方案1】:

    这是因为 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;
        }
    

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多