tags:

views:

70

answers:

3

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;
+1  A: 

Have you tried a foreach() loop? That should give you all the accessible elements, and the keys it returns may give you a better clue as to how to access them directly.

Spudley
<b>Fatal error</b>: Cannot use object of type stdClass as array
Ben Guthrie
what version of PHP are you using? As of PHP5, you should be able to use `foreach` on an object. (if you're still using PHP4, you should upgrade as it's been end-of-life for over two years)
Spudley
+1 as this would have worked on supported versions of PHP anyway. Definitely looks like a PHP 4 case here.
BoltClock
A: 
pixeline
<b>Fatal error</b>: Cannot use object of type stdClass as array in <b>file.php</b> on line <b>44</b><br />
Ben Guthrie
i updated my answer. In short, i don't think that is possible out of the box but it can be implemented.
pixeline
+3  A: 

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.

BoltClock
YES! Thank you.
Ben Guthrie
Are you sure that works? On PHP 5.3, it yields `Undefined property: stdClass::$0`, which is what my experience has always been.
konforce
@konforce: I think my suggestion works on PHP 4, which would be what I assume OP is running since Spudley's answer doesn't work.
BoltClock
In that case, I'd add something like `if (version_compare(PHP_VERSION, '5.0.0', '>=')) die('PHP 5 is not supported');` or at least a big warning as a comment that the code is not forward compatible.
konforce