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 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题