【发布时间】:2021-01-03 09:35:01
【问题描述】:
我想获取带有参数的特定 url 的 jsonfile 内容的一部分。 我有一个 results.json 文件,其中包含以下内容:
{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "8422"
}
]
}
我有一个 php 文件,我想通过以下链接获取并显示来自 for exmaple id = 1 的部分 json 输出
/api.php?id=1
<?php
header("Content-Type:application/json");
function get_feed($getid)
{
$json = file_get_contents('results3.json');
$feeds = json_decode($json);
foreach($feeds as $feed=>$id)
{
if($id==$getid)
{
return $name;
break;
}
}
}
if(!empty($_GET['id']))
{
$getid=$_GET['id'];
$feed = get_feed($getid);
if(empty($feed))
{
response(200,"Data Not Found",NULL);
}
else
{
response(200,"Data Found",$feed);
}
}
else
{
response(400,"Invalid Request",NULL);
}
function response($status,$status_message,$data)
{
header("HTTP/1.1 ".$status);
$response['status']=$status;
$response['status_message']=$status_message;
$response['data']=$data;
$json_response = json_encode($response);
echo $json_response;
}
但结果我在点击链接 /api.php?id=1 时得到了这个
{"status":200,"status_message":"Data Not Found","data":null}
我没有正确地通过数组。 任何帮助表示赞赏! 提前谢谢!
【问题讨论】: