简体   繁体   中英

PHP array cannot get value from key

I got an object that has some private properties that i cannot access.

var_dump($roomType);

// I deleted some of the results of var_dump
object(MPHB\Entities\RoomType)#2003 (6) {
["id":"MPHB\Entities\RoomType":private]=> int(15) 
["originalId":"MPHB\Entities\RoomType":private]=> int(15) 
["description":"MPHB\Entities\RoomType":private]=> string(0) "" 
["excerpt":"MPHB\Entities\RoomType":private]=> string(0) ""  
["imageId":"MPHB\Entities\RoomType":private]=> int(406) 
["status":"MPHB\Entities\RoomType":private]=> string(7) "publish" }

So I convert the object to array.

$array = (array) $roomType;

print_r($array);
/*
Array (
[MPHB\Entities\RoomTypeid] => 15
[MPHB\Entities\RoomTypeoriginalId] => 15
[MPHB\Entities\RoomTypedescription] =>
[MPHB\Entities\RoomTypeexcerpt] =>
[MPHB\Entities\RoomTypeimageId] => 406
[MPHB\Entities\RoomTypestatus] => publish )
*/

but I still cannot access the values from key like this

var_dump($array["MPHB\Entities\RoomTypeimageId"]); // NULL

The only workaround i got is this:

$array = (array) $roomType;

$array_keys = array_keys($array);
$array_key_id = $array_keys[4];

echo $array[$array_key_id]; // 406

But I am not sure that the key is at the same position all the time, so I want to find an other way.

I escaped the slashes but still the same, any ideas?

Edit:

So I tried to compare the $array_key_id (which is MPHB\Entities\RoomTypeimageId) with the same value (copied from the browser) and it fails.

So I did a loop and pushed the key=>value to the existing $array and now I can get the value.

There must be something like null bytes as BacLuc said.

I would guess that escaping is the problem: $array["MPHB\Entities\RoomTypeimageId"] -> $array["MPHBEntitiesRoomTypeimageId"] for which there is no value in the array.

But $array["MPHB\\Entities\\RoomTypeimageId"] might work.

Edit: it's escaping plus on private properties have the class name prepended to the property name, surrounded with null bytes.

Test is here: http://sandbox.onlinephpfunctions.com/code/d218d41f22e86dd861f562de9c040febb011d577

From:

Convert a PHP object to an associative array

https://www.php.net/manual/en/language.types.array.php#language.types.array.casting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM