How to access object properties with names like integers?

后端 未结 7 1102
故里飘歌
故里飘歌 2020-11-21 22:14

I am using json_decode() something like:

$myVar = json_decode($data)

Which gives me output like this:

[highlig         


        
7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 23:11

    Just wanted to add to Jon's eloquent explanation the reason why this fails. It's all because when creating an array, php converts keys to integers — if it can — which causes lookup problems on arrays which have been cast to objects, simply because the numeric key is preserved. This is problematic because all property access options expect or convert to strings. You can confirm this by doing the following:

    $arr = array('123' => 'abc');
    $obj = (object) $arr;
    $obj->{'123'} = 'abc';
    print_r( $obj );
    

    Which would output:

    stdClass Object ( 
      [123] => 'abc', 
      [123] => 'abc'
    )
    

    So the object has two property keys, one numeric (which can't be accessed) and one string based. This is the reason why Jon's #Fact 4 works, because by setting the property using curly braces means you always define a string-based key, rather than numeric.

    Taking Jon's solution, but turning it on its head, you can generate an object from your array that always has string-based keys by doing the following:

    $obj = json_decode(json_encode($arr));
    

    From now on you can use either of the following because access in this manner always converts the value inside the curly brace to a string:

    $obj->{123};
    $obj->{'123'};
    

    Good old illogical PHP...

提交回复
热议问题