【问题标题】:Get specific data from Json File with an url with parameters使用带参数的 url 从 Json 文件中获取特定数据
【发布时间】: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}

我没有正确地通过数组。 任何帮助表示赞赏! 提前谢谢!

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    您对 JSON 的结构和实际阅读方式有疑问:

    JSON 结构:

    {
      'data' => array(
         {},
         {},
      )
    }
    

    您 JSON 的 data 包含数组。

    你把它读成:

    foreach($feeds as $feed=>$id)
    {
        if($id==$getid)
        {
            return $name;
            break;
        }
    }
    

    看到您查看了根 JSON 对象,但没有读取 data 的实际数组内容

    应该是这样的:

    $feeds = json_decode($json, true);
    foreach($feeds['data'] as $eachData)
    {
        if($eachData['id']==$getid)
        {
            return $eachData['name'];
            //no need for break, as it is not accessible because of return above.
            //break;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 2023-04-04
      • 2021-06-22
      相关资源
      最近更新 更多