Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return PHP object by index number (not name)

Tags:

object

php

Goal: retrieve an element of data from within a PHP object by number.

This is the print_r($data) of the object:

stdClass Object
(
    [0] => stdClass Object
        (
            [TheKey] => 1456
            [ThingName] => Malibu
            [ThingID] => 7037
            [MemberOf] => California
            [ListID] => 7035
            [UserID] => 157
            [UserName] => John Doe
        )
)

I can't figure out how to pull a value out of it. This is only one record of a multi-record object that should be by id rather than a name.

These are some failed attempts to illustrate what the goal is:

echo $data -> 0 -> UserName;
echo $data[0] -> UserName;
like image 275
Ben Guthrie Avatar asked Oct 03 '10 20:10

Ben Guthrie


3 Answers

Normally, PHP variable names can't start with a digit. You can't access $data as an array either as stdClass does not implement ArrayAccess — it's just a normal base class.

However, in cases like this you can try accessing the object attribute by its numeric name like so:

echo $data->{'0'}->UserName;

The only reason I can think of why Spudley's answer would cause an error is because you're running PHP 4, which doesn't support using foreach to iterate objects.

like image 133
BoltClock Avatar answered Nov 19 '22 03:11

BoltClock


BoltClock's suggestion to use "$data->{'0'}->UserName" apparently no longer works with PHP 5.

I had the same problem and I found that current() will work to get that numbered class element like this...

echo current($data)->UserName;

Or if that doesn't work (depending on the object) you may need to do another current() call like this:

echo current(current($data))->UserName;
like image 32
orrd Avatar answered Nov 19 '22 04:11

orrd


this works for PHP5+

echo $data[0]->UserName;

or

foreach ($data as $data){
    echo $data->UserName;
    }

or as suggested by @orrd

current($data)->UserName works great too.
like image 4
Pageii Studio Avatar answered Nov 19 '22 05:11

Pageii Studio