Return PHP object by index number (not name)

后端 未结 5 789
不思量自难忘°
不思量自难忘° 2020-11-30 08:13

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] => stdCl         


        
相关标签:
5条回答
  • 2020-11-30 08:28

    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;
    
    0 讨论(0)
  • 2020-11-30 08:28

    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.
    
    0 讨论(0)
  • 2020-11-30 08:31

    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.

    0 讨论(0)
  • 2020-11-30 08:46

    try this:

    echo $data[0]['UserName'];
    

    According to the manual, objects are not meant to be used that way. The comments on this page do provide a way around if that's a must-have for you. You could also simply rely on arrays if you are just using the object for properties (and not behaviours).

    0 讨论(0)
  • 2020-11-30 08:48

    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.

    0 讨论(0)
提交回复
热议问题