Get first element in PHP stdObject

后端 未结 7 1121
日久生厌
日久生厌 2020-12-05 09:23

I have an object (stored as $videos) that looks like this

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    [\"id\"]=>
    string(1) \         


        
相关标签:
7条回答
  • 2020-12-05 09:41

    much easier:

    $firstProp = current( (Array)$object );
    
    0 讨论(0)
  • 2020-12-05 09:48

    $videos->{0}->id worked for me.

    Since $videos and {0} both are objects, so we have to access id with $videos->{0}->id. The curly braces are required around 0, as omitting the braces will produce a syntax error : unexpected '0', expecting identifier or variable or '{' or '$'.

    I'm using PHP 5.4.3.

    In my case, neither $videos{0}->id and $videos{0}['id'] worked and shows error :

    Cannot use object of type stdClass as array.

    0 讨论(0)
  • 2020-12-05 09:49

    Correct:

    $videos= (Array)$videos;
    $video = $videos[0];
    
    0 讨论(0)
  • 2020-12-05 10:03

    Playing with Php interactive shell, Php 7:

    ➜  ~ php -a
    Interactive shell
    
    php > $v = (object) ["toto" => "hello"];
    php > var_dump($v);
    object(stdClass)#1 (1) {
      ["toto"]=>
      string(5) "hello"
    }
    php > echo $v{0};
    PHP Warning:  Uncaught Error: Cannot use object of type stdClass as array in php shell code:1
    Stack trace:
    #0 {main}
      thrown in php shell code on line 1
    
    Warning: Uncaught Error: Cannot use object of type stdClass as array in php shell code:1
    Stack trace:
    #0 {main}
      thrown in php shell code on line 1
    php > echo $v->{0};
    PHP Notice:  Undefined property: stdClass::$0 in php shell code on line 1
    
    Notice: Undefined property: stdClass::$0 in php shell code on line 1
    php > echo current($v);
    hello
    

    Only current is working with object.

    0 讨论(0)
  • 2020-12-05 10:07

    Update 2019

    Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

    Simply iterate its using {}

    Example:

    $videos{0}->id
    

    This way your object is not destroyed and you can easily iterate through object.

    For PHP 5.6 and below use this

    $videos{0}['id']
    
    0 讨论(0)
  • 2020-12-05 10:07

    Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

    So, if your object looks like

    object(stdClass)#19 (3) {
      [0]=>
      object(stdClass)#20 (22) {
        ["id"]=>
        string(1) "123"
      etc...
    

    Then you can just do;

    $id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object
    

    If you need the key for some reason, you can do;

    reset($obj); //Ensure that we're at the first element
    $key = key($obj);
    

    Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4

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