How to access a property of an object (stdClass Object) member/element of an array? [duplicate]
Asked Answered
C

5

46

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 
        ) 
)

How can I access a specific value in the array? The following code does not work because of the stdClass Object

echo $array['id'];
Charleencharlemagne answered 16/1, 2014 at 17:14 Comment(2)
echo $array[0]->id;Isologous
#12277768Astrograph
P
95

To access an array member you use $array['KEY'];

To access an object member you use $obj->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;
}

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 :)

Update (this might help someone understand better):

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):

First method:

$colorPallete = ['red', 'blue', 'green'];

The above array will be assigned numeric keys automatically. So the key assigned to red will be 0, for blue 1 and so on.

Getting values from the above array:

$colorPallete[0]; // will output 'red'
$colorPallete[1]; // will output 'blue'
$colorPallete[2]; // will output 'green'

Second method:

$colorPallete = ['love' => 'red', 'trust' => 'blue', 'envy' => 'green']; // we expliicitely define the keys ourself.

Getting values from the above array:

$colorPallete['love']; // will output 'red'
$colorPallete['trust']; // will output 'blue'
$colorPallete['envy']; // will output 'green'
Prosit answered 16/1, 2014 at 17:17 Comment(6)
thanks, I thought it would be something simpleCharleencharlemagne
hey i didnt understood the use of $value here ..?..and yeah am new to php ..is it a new variable that we create it for finding the key value ?Astrograph
@CodeLover if for example we have an array $a = ['someKey' => 'someValue']; then you will get someValue returned if you access $a['someKey']. When we use the foreach loop we can access the key and value for each member of an array.Prosit
@LuckySoni hey i knew it .but i want to know echo $value->KEY ..what does it do ..when i tried in code ..it doesnt echoed anythingAstrograph
@CodeLover In the answer above the $value is an Object. We are accessing the key on an Object using the Object->key notation. Hope this makes sense.Prosit
how do I compare $key to a string?Zr
R
28

Try this, working fine -

$array = json_decode(json_encode($array), true);
Rabble answered 10/6, 2015 at 9:40 Comment(2)
Thanks! Why does adding true converts to array ?Dinodinoflagellate
@Dinodinoflagellate yes it's for return array. eg. - json_decode('{"foo":"bar"}', true); returns array("foo" => "bar");Rabble
P
13

Try this:

echo $array[0]->id;
Plane answered 16/1, 2014 at 17:17 Comment(3)
Try this answers are low value on StackOverflow because they do very little to educate the OP and future readers. Please endeavor to improve this answer regardless of the simplicity of the solution.Eroto
I upvoted this answer but I agree with @mickmackusa, 'Try this' responses are extremely low value on Stack Overflow and I wish S.O. would disallow them frankly. Please give at least some explanation of your proposed solution -even one sentence is enough.Buoyancy
I NEVER uv a code-only answer because it will send the wrong message that all it takes is a snippet to gain unicorn points. The way to making SO better is to only support good content. @EightEroto
A
3

You have an array. A PHP array is basically a "list of things". Your array has one thing in it. That thing is a standard class. You need to either remove the thing from your array

$object = array_shift($array);
var_dump($object->id);

Or refer to the thing by its index in the array.

var_dump( $array[0]->id );

Or, if you're not sure how many things are in the array, loop over the array

foreach($array as $key=>$value)
{
    var_dump($value->id);
    var_dump($array[$key]->id);
}
Analyse answered 16/1, 2014 at 17:20 Comment(0)
P
0

How about something like this.

function objectToArray( $object ){
   if( !is_object( $object ) && !is_array( $object ) ){
    return $object;
 }
if( is_object( $object ) ){
    $object = get_object_vars( $object );
}
    return array_map( 'objectToArray', $object );
}

and call this function with your object

$array = objectToArray( $yourObject );

reference

Poacher answered 5/3, 2016 at 18:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.