[英]JSON to PHP Associative array
你們中有人知道將它放入關聯數組的好方法嗎? 我試過json_decode
但發現它沒有多大幫助。
這是我需要放入關聯數組的數據:
{
"data": [
{
"name": "Joe Bloggs",
"id": "203403465"
},
{
"name": "Fred Bloggs",
"id": "254706567"
},
{
"name": "Barny Rubble",
"id": "453363843"
},
{
"name": "Homer Simpson",
"id": "263508546"
}
]
}
編輯:
接受答案后,我想起了為什么我認為 json_decode 不起作用。
而不是擁有這樣的關聯數組:
[0] => Array
(
[name] => Joe Bloggs
[id] => 203403465
)
我想要一個這樣的:
Array
(
[Joe Bloggs] => 45203340465
[Fred Bloggs] => 65034033446
)
不幸的是,我當時忘記了這一點......但我現在已經解決了我的問題。
感謝您所有的幫助!
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));
輸出:
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
)
)
)
將第二個參數設置為true
返回一個關聯數組。
你必須創建一個新數組
$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'];
}
您將在 $assoc_array 中獲得關聯數組,現在可以使用索引直接訪問。
我假設你的 json 來自 ajax ......(否則代碼與 json_decode 一起工作)所以確保 js json 字符串化你的對象和
你需要在 json_decode 之前去掉斜杠;-) 在 php 中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.