如何访问数组的对象(stdClass 对象)成员/元素的属性? [英] How to access a property of an object (stdClass Object) member/element of an array?
问题描述
在我的数组上执行 print_r()
我得到以下结果:
Doing print_r()
on my array I get the following:
Array (
[0] =>
stdClass Object
(
[id] => 25
[time] => 2014-01-16 16:35:17
[fname] => 4
[text] => 5
[url] => 6
)
)
如何访问数组中的特定值?由于 stdClass 对象,以下代码不起作用
How can I access a specific value in the array? The following code does not work because of the stdClass Object
echo $array['id'];
推荐答案
要访问数组成员,请使用 $array['KEY'];
To access an array member you use $array['KEY'];
要访问对象成员,请使用 $obj->KEY;
To access an object member you use $obj->KEY;
要访问对象数组中的对象成员:$array[0]
//获取数组中的第一个对象$array[0]->KEY
//然后访问它的密钥
To access an object member inside an array of objects:
$array[0]
// Get the first object in the array
$array[0]->KEY
// then access its key
你也可以像这样循环遍历一个对象数组:
You may also loop over an array of objects like so:
foreach ($arrayOfObjs as $key => $object) {
echo $object->object_property;
}
将数组视为事物的集合.这是一个袋子,您可以在其中存储您的东西并给它们一个唯一的 ID(密钥)并使用该密钥访问它们(或从袋子中取出东西).我想在这里保持简单,但这个包也可以装其他包:)
Think of an array as a collection of things. It's a bag where you can store your stuff and give them a unique id (key) and access them (or take the stuff out of the bag) using that key. I want to keep things simple here, but this bag can contain other bags too :)
一个数组包含 'key
' 和 'value
' 对.为数组成员提供键是可选的,在这种情况下,它会自动分配一个数字键,该键从 0 开始,并为每个附加成员继续增加 1.我们可以通过它的key
"从数组中检索一个值".
An array contains 'key
' and 'value
' pairs. Providing a key for an array member is optional and in this case it is automatically assigned a numeric key which starts with 0 and keeps on incrementing by 1 for each additional member. We can retrieve a 'value' from the array by it's 'key
'.
所以我们可以通过以下方式定义一个数组(关于键):
So we can define an array in the following ways (with respect to keys):
$colorPallete = ['red', 'blue', 'green'];
上述数组将自动分配数字键.因此分配给红色的键将为 0,蓝色为 1,依此类推.
The above array will be assigned numeric keys automatically. So the key assigned to red will be 0, for blue 1 and so on.
$colorPallete[0]; // will output 'red'
$colorPallete[1]; // will output 'blue'
$colorPallete[2]; // will output 'green'
第二种方法:
$colorPallete = ['love' => 'red', 'trust' => 'blue', 'envy' => 'green']; // we expliicitely define the keys ourself.
从上述数组中获取值:
$colorPallete['love']; // will output 'red'
$colorPallete['trust']; // will output 'blue'
$colorPallete['envy']; // will output 'green'
这篇关于如何访问数组的对象(stdClass 对象)成员/元素的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!