dongmaopiao0901 2011-11-28 21:13
浏览 42
已采纳

PHP,json_decode,数组问题

I have a multi-dimensional associative array that is encoded into JSON for database storage, and then decoded for display. I am having trouble accessing the resulting array elements.

An example JSON string:

{
    "service": "Star Break Repair",
    "options": {
        "Buy with me -60": "-60.00",
        "Bulseye Break Repair": "30.00"
    }
}

After decoding this using json_decode($array, true) (true gets an array, not an object), I get an array as expected:

Array
(
    [service] => Star Break Repair
    [options] => Array
        (
            [Buy with me -60] => -60.00
            [Bulseye Break Repair] => 30.00
        )

)

But when I try and echo a specific element:

echo @key($services['options'][0]);

or

echo $services['options'][0];

I get nothing, blank.

When I try to:

key($services['options'][0])

I get this error:

key() [function.key]: Passed variable is not an array or object in... 

I've tried saving the options array as its own PHP variable, and the same thing happens. I can print_r() either array (the original with the nested options array, or just the options array), but when I try and print a specific element, nothing happens. When I try and print the element key, I get that PHP error.

What's going on?

  • 写回答

4条回答 默认 最新

  • duanluo9369 2011-11-28 21:21
    关注

    The issue is that you have an associative array for your options, not an integer-indexed array.

    So, if you want to access the elements of options you need to refer to them by their string keys:

    $foo = $services['options']['Buy with me -60'];
    $bar = $services['options']['Bulseye Break Repair'];
    

    Now, if you don't know the keys, you can use a foreach loop to iterate over your options array:

    foreach($services['options'] as $okey=>$oval) {
        echo $okey; //'Buy with me -60', 'Bulseye Break Repair'
        echo $oval; //'-60.00', '30.00'
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码