dongzhanlu8890 2013-01-17 15:09 采纳率: 0%
浏览 66
已采纳

无法通过索引获取数组的对象

EDITED: I am generating a 2D array and storing it in db as json string. When I need to modify anything in the array, I then fetch the json string and decode it like

$myarray = (array)json_decode($jsonString);

The dump of array is as

enter image description here

$index = 2;

When I wan to access object at index '2' like $myarray[$index] I get null. Please guide what I am doing wrong?

  • 写回答

2条回答 默认 最新

  • dongya0914 2013-01-17 15:35
    关注

    In your comment you said this "array" was decoded from JSON. When you use json_decode, send true as the 2nd parameter. That tells it to make arrays instead of objects when decoding.

    You're having trouble because the array is being decoded as an object, which you access using -> instead of [].

    $newArray = json_decode($jsonString, true);
    

    UPDATE: You were trying to do (array)json_decode($jsonString) and that wasn't working. That's because PHP is silly when it comes to type-casting.

    Here's a quote from the PHP docs:

    If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour.

    Source: http://php.net/manual/en/language.types.array.php#language.types.array.casting

    So, it wasn't working because PHP said so.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000