【问题标题】:Accessing Object within Array访问数组中的对象
【发布时间】:2023-03-30 19:27:01
【问题描述】:

我有以下输出:

Array (
  [0] => stdClass Object (
        [id] => 20
        [news_title] => Startup finance docs in GitHub
        [news_url] => http://venturebeat.com/2013/03/06/fenwick-west-github/
        [news_root_domain] => venturebeat.com
        [news_category] =>
        [news_submitter] => 4
        [news_time] => 2013-03-06 11:20:03
        [news_points] => 0
    )
    [1] => stdClass Object (
        [id] => 21
        [news_title] => The problems with righteous investing
        [news_url] => http://gigaom.com/2013/03/07/the-problems-with-righteous-investing/
        [news_root_domain] => gigaom.com
        [news_category] =>
        [news_submitter] => 4
        [news_time] => 2013-03-08 09:14:17
        [news_points] => 0
    )
)

我如何访问这些中的 news_url 之类的内容?我已经尝试过,但无济于事:

print_r $this->$record[0]->news_title;

【问题讨论】:

  • 你可能想要:print_r $this->record[0]->news_title;,注意我删除了$record[0]中的$

标签: php arrays object multidimensional-array


【解决方案1】:

试试这个:

 $arr =    Array();

    $obj0 = new stdClass;
    $obj0->id = 123;
    $obj0->news_title = "some title 0";
    //etc...
    $obj1 = new stdClass;
    $obj1->id = 124;
    $obj1->news_title = "some title 1";
    //etc...

   $arr[0] = $obj0;
   $arr[1] = $obj1;

    print_r($arr);

或类似的东西

print_r($arr[0]);

甚至

 echo $arr[0]->id;

【讨论】:

    【解决方案2】:

    您正在使用类属性,您可能需要先检查它是否可访问。在使用$this 后访问类属性时,您不需要额外的$,只需使用$this - record。喜欢

    echo $this -> record[0] -> title;
    

    如果record 是一个有效的类属性,它是一个数组,但它仍然不起作用。也试试这个:

    echo {$this -> record[0]} -> title;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多