[英]PHP array cannot get value from key
I got an object that has some private properties that i cannot access.我有一个 object 有一些我无法访问的私有属性。
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.所以我将 object 转换为数组。
$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.但是我不确定钥匙是否一直在同一个 position ,所以我想找到其他方法。
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.因此,我尝试将
$array_key_id
(即 MPHB\Entities\RoomTypeimageId)与相同的值(从浏览器复制)进行比较,但失败了。
So I did a loop and pushed the key=>value to the existing $array
and now I can get the value.所以我做了一个循环并将 key=>value 推送到现有的
$array
中,现在我可以获取该值。
There must be something like null bytes as BacLuc said.正如 BacLuc 所说,必须有像 null 字节这样的东西。
I would guess that escaping is the problem: $array["MPHB\Entities\RoomTypeimageId"] -> $array["MPHBEntitiesRoomTypeimageId"] for which there is no value in the array.我猜想 escaping 是问题所在: $array["MPHB\Entities\RoomTypeimageId"] -> $array["MPHBEntitiesRoomTypeimageId"] 数组中没有值。
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.编辑:它的 escaping 加上私有属性有 class 名称附加到属性名称,用 null 字节包围。
Test is here: http://sandbox.onlinephpfunctions.com/code/d218d41f22e86dd861f562de9c040febb011d577测试在这里: http://sandbox.onlinephpfunctions.com/code/d218d41f22e86dd861f562de9c040febb011d577
From:从:
Convert a PHP object to an associative array 将 PHP object 转换为关联数组
https://www.php.net/manual/en/language.types.array.php#language.types.array.casting https://www.php.net/manual/en/language.types.array.php#language.types.array.casting
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.