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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?