[英]JSON to PHP Associative array
would any of you know a good way to put this into an associative array .你们中有人知道将它放入关联数组的好方法吗? I have tried json_decode
but found it to not be much help.我试过json_decode
但发现它没有多大帮助。
This is the data i need to put into an associative array:这是我需要放入关联数组的数据:
{
"data": [
{
"name": "Joe Bloggs",
"id": "203403465"
},
{
"name": "Fred Bloggs",
"id": "254706567"
},
{
"name": "Barny Rubble",
"id": "453363843"
},
{
"name": "Homer Simpson",
"id": "263508546"
}
]
}
EDIT:编辑:
After I accepted the answer, I remembered why I thought that the json_decode wasn't working.接受答案后,我想起了为什么我认为 json_decode 不起作用。
Instead of having an associative array like this:而不是拥有这样的关联数组:
[0] => Array
(
[name] => Joe Bloggs
[id] => 203403465
)
I wanted one like this:我想要一个这样的:
Array
(
[Joe Bloggs] => 45203340465
[Fred Bloggs] => 65034033446
)
Unfortunately, I had forgotten this at the time.. but I have resolved my issue now anyway.不幸的是,我当时忘记了这一点......但我现在已经解决了我的问题。
Thanks for all of your help!感谢您所有的帮助!
json_decode works for me on your data: json_decode对我的数据有用:
print_r(json_decode('{
"data": [
{
"name": "Joe Bloggs",
"id": "203403465"
},
{
"name": "Fred Bloggs",
"id": "254706567"
},
{
"name": "Barny Rubble",
"id": "453363843"
},
{
"name": "Homer Simpson",
"id": "263508546"
}
]
}
', true));
Output:输出:
Array
(
[data] => Array
(
[0] => Array
(
[name] => Joe Bloggs
[id] => 203403465
)
[1] => Array
(
[name] => Fred Bloggs
[id] => 254706567
)
[2] => Array
(
[name] => Barny Rubble
[id] => 453363843
)
[3] => Array
(
[name] => Homer Simpson
[id] => 263508546
)
)
)
Setting the second argument to true
returns an associative array.将第二个参数设置为true
返回一个关联数组。
You have to make a new array你必须创建一个新数组
$json_array = json_decode($_POST['json'], true);
$assoc_array = array();
for($i = 0; $i < sizeof($json_array); $i++)
{
$key = $json_array[$i]['name'];
$assoc_array[$key] = $json_array[$i]['value'];
}
you will get your associative array in $assoc_array and you can now directly access using indexes.您将在 $assoc_array 中获得关联数组,现在可以使用索引直接访问。
i asume your json comes via ajax.... (otherwise the code works with json_decode) so be sure the js json stringifys your object and我假设你的 json 来自 ajax ......(否则代码与 json_decode 一起工作)所以确保 js json 字符串化你的对象和
you'll need to stripslashes before json_decode ;-) in php你需要在 json_decode 之前去掉斜杠;-) 在 php 中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.