PHP Array of a stdClass, How to get data?
Asked Answered
S

4

7

I would like to print the value of [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.

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?

Seger answered 24/4, 2012 at 17:3 Comment(0)
D
5

The only array key listed is [3] (Array ( [3] => stdClass...), so use

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.

Get them all with a loop:

foreach ($terms as $t) {
   echo $t->name;
}
Deannedeans answered 24/4, 2012 at 17:5 Comment(1)
you beat me to it with 5sec ... nice oneBridie
P
2

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']
Plethora answered 24/4, 2012 at 17:9 Comment(0)
B
1

You can use the following :

echo $terms[3]->name ;
Bridie answered 24/4, 2012 at 17:5 Comment(0)
C
0

To display the value of the objects fiel name, you can use this command:

    echo $this[3]->name;
Captor answered 8/7, 2015 at 6:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.