用PHP编译完整json的编码段

问题描述 投票:0回答:2

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

这是我的设置,我不确定我需要在我的PHP脚本中定义什么来从json中的长列表中获取此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"
    }
}
php json echo
2个回答
1
投票

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

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

$echome = $decode[$id];

请注意,truejson_decode()接受的第二个参数。你可以阅读更多关于它here


0
投票

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

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

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

$echome = $decode->{$id};           //looking for "id" within the json
© www.soinside.com 2019 - 2024. All rights reserved.