php 访问数组中的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16409190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing Object within Array
提问by viablepath
I have the following output:
我有以下输出:
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
)
)
How would I access something like news_url in these? I've tried this, but to no avail:
我将如何访问这些中的 news_url 之类的东西?我试过这个,但无济于事:
print_r $this->$record[0]->news_title;
回答by Tucker
try this:
尝试这个:
$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);
or something like
或类似的东西
print_r($arr[0]);
or even
甚至
echo $arr[0]->id;
回答by Starx
You are using class property, you might want to check if it is accessible first. While accessing the class property after using $this
you dont need the additional $
, just use $this - record
. Like
您正在使用类属性,您可能想先检查它是否可访问。使用后访问类属性时$this
不需要额外的$
,只需使用$this - record
. 喜欢
echo $this -> record[0] -> title;
If record
is a valid class property which is an array and it still does not work. Give this a try too:
Ifrecord
是一个有效的类属性,它是一个数组,但它仍然不起作用。也试试这个:
echo {$this -> record[0]} -> title;