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条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失