简体   繁体   English

PHP数组的stdClass,如何获取数据?

[英]PHP Array of a stdClass, How to get data?

I would like to print the value of [name]. 我想打印[name]的值。 I am just becoming familiar with standard defined classes and how they are called. 我只是熟悉标准定义的类以及如何调用它们。

Based on this example and logic 基于这个例子和逻辑

$arrayobj = new ArrayObject(array('first','second','third'));
print_r($arrayobj);
//outputs: ArrayObject Object ( [0] => first [1] => second [2] => third )

With that. 接着就,随即。 I'm trying to extract the value of name (Pebbles) out of here. 我试图从这里提取名称(Pebbles)的值。

print_r($terms);
/* outputs
Array ( [3] => stdClass Object ( [term_id] => 3 [name] => Pebbles ) )
*/

So I tried 所以我试过了

echo $terms[0]->name;

Got peanuts. 有花生。 How do I do this? 我该怎么做呢?

The only array key listed is [3] ( Array ( [3] => stdClass... ), so use 列出的唯一数组键是[3]Array ( [3] => stdClass... ),所以使用

echo $terms[3]->name;

Even though it is a numerically indexed array, that doesn't mean it starts with an index of 0 or even has sequential keys. 尽管它是一个数字索引数组,但这并不意味着它以索引0开始,甚至不具有顺序键。

Get them all with a loop: 通过循环获取它们:

foreach ($terms as $t) {
   echo $t->name;
}

Correct me if I am wrong, but you can typecast them. 如果我错了,请纠正我,但你可以对它们进行类型化。

$terms = (array) $terms;

Will make it a normal array accessible through: 将通过以下方式使其成为正常的数组:

$terms[3]['name']

您可以使用以下内容:

echo $terms[3]->name ;

要显示对象名称的值,可以使用以下命令:

    echo $this[3]->name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM