解码多值JSON

时间:2015-02-02 05:45:21

标签: php json

我试图创建一个需要解码的游戏API,但我不确定(这只适用于某个用户,因此值不一样)

[
    {
        "Id": 382779,
        "Name": "DarkAge Ninjas"
    },
    {
        "Id": 377291,
        "Name": "Emerald Knights of the Seventh Sanctum"
    },
    {
        "Id": 271454,
        "Name": "Knights of RedCliff"
    },
    {
        "Id": 288278,
        "Name": "Knights of the Splintered Skies "
    },
    {
        "Id": 375307,
        "Name": "Korblox's Empire"
    },
    {
        "Id": 387867,
        "Name": "Ne'Kotikoz"
    },
    {
        "Id": 696519,
        "Name": "Orinthians"
    },
    {
        "Id": 27770,
        "Name": "Retexture Artists Official Channel"
    },
    {
        "Id": 585932,
        "Name": "Retexturing Apprentices "
    },
    {
        "Id": 7,
        "Name": "Roblox"
    },
    {
        "Id": 679727,
        "Name": "ROBLOX Community Staff and Forum Users"
    },
    {
        "Id": 127081,
        "Name": "Roblox Wiki"
    }
]

如何在PHP中对此进行解码,以便它具有类似

的列表

DarkAge Ninjas Emerald Knights of the Seventh Sanctum Knights of RedCliff

等,并将Id单独解码,以便我可以创建一个可点击的链接:/

1 个答案:

答案 0 :(得分:1)

您需要json_decode将json转换为php数组

$api_json = '[
    { "Id": 382779, "Name": "DarkAge Ninjas" }, 
    { "Id": 377291, "Name": "Emerald Knights of the Seventh anctum" }
    ...
]';

$api_data = json_decode($api_json, true);

//Now you can loop over the array and print the `Name`
foreach($api_data as $d) {
   echo $d['Name'];
}

上面的代码将输出

DarkAge Ninjas 
Emerald Knights of the Seventh Sanctum 
Knights of RedCliff
...

要与ID建立链接,只需在上面的循环中添加

echo '<a href="'. $d['Id'].'">'. $d['Name'].'</a>';

正如Ed Cottrell建议的那样,阅读手册:json_decode了解更多