用 PHP 回显完整 json 的编码片段

Echo encoded segment of of a full json with PHP

我正在为我的 json 文件设置一个简单的 PHP 处理程序。

这是我的设置,我不确定我需要在 PHP 脚本中定义什么才能从 json.[=15= 的长列表中获取此 ID ]

如有任何建议或帮助,我们将不胜感激。

<?php
$id = $_GET['id'];              //get ?id=
$jsonurl = "api/documents.json";     //json path
$json = file_get_contents($jsonurl);   //getting file
$decode = json_decode($json);          //decoding the json

$echome = $decode[0]->$id;           //looking for "id" within the json

$reencode = json_encode($echome)     //re-encoding this segmented json

echo($reencode);        //echo the json

期望的结果是

//load page with id set as 21
{
    "21": {
        "name": "mike",
        "active": "yes"
    }
}

url = www.example.com/process.php?id=21

// simple example of the json
{
    "20": {
        "name": "john",
        "active": "no"
    },
    "21": {
        "name": "mike",
        "active": "yes"
    }
}

如果您想将其作为数组访问,通过将 true 传递给 json_decode 作为关联数组进行解码,然后:

$echome = $decode[$id];           //looking for "id" within the json

或者,如果您想将其保留为对象,您可以通过执行以下操作来访问属性:

$echome = $decode->{$id};           //looking for "id" within the json

$decode不是一个数组,它是一个对象,所以你最好把它解码成一个数组,然后访问键如下:

$id     = $_GET['id'];           
$decode = json_decode($json, true);

$echome = $decode[$id];

请注意 truejson_decode() 接受的第二个参数。您可以阅读更多相关信息 here