Return PHP object by index number (not name)

后端 未结 5 799
不思量自难忘°
不思量自难忘° 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: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.

提交回复
热议问题