通过解析url中的数组名称从JSON文件中获取数组

时间:2017-04-18 00:16:40

标签: php json

我有这个JSON文件:

alldata.json

{
"players": [
    {
        "name": "Marcos Alonso",
        "position": "Left-Back",
        "nationality": "Spain",
        "marketValue": "9,000,000 €",
        "created": "2017-04-15 10:04:58"
    }],

"articles": [
{
    "author": "Stephen Walter",
    "title": "Disruptive stag party revellers thrown off plane at Manchester Airport",
    "url": "http://www.telegraph.co.uk/news/2017/04/15/disruptive-stag-party-revellers-thrown-plane-manchester-airport/",
    "publishedAt": "2017-04-15T09:25:10Z"
}],

"land": [
{
    "state": "Somewhr",
    "found": "1889",
    "area": "6,812",
    "empl": "1,325",
    "ppl": "16,842"

}]
}

然后我有这个php文件:

getSeacrh.php

$url = ('alldata.json');
$jsondata = file_get_contents($url);

//convert json object to php associative array
$data = json_decode($jsondata, true);

$mySearch = $_GET['search']; //to get array that I want
if (!$mySearch) {
    echo 'No search';
} else {
    //I would need help here
    foreach ($data as $value) { //what can I do here to get just only searched array 
        $srch = $value[$mySearch]; //and not all arrays in the json file?
    }

    header('Content-Type: application/json; charset=UTF-8');
    $json_string = json_encode($temp, JSON_PRETTY_PRINT);
    print $json_string;
}

请帮助我做什么,这样当我执行我的php文件(getSearch.php)时,例如“http://localhost/test/getsearch.php?search=players”我将只获得“玩家”数组。此外,如果我解析文件中的其他数组名称,它将只给我这个数组。以下是我的意思的一个例子:

 {
    "players": [
        {
            "name": "Marcos Alonso",
            "position": "Left-Back",
            "nationality": "Spain",
            "marketValue": "9,000,000 €",
            "created": "2017-04-15 10:04:58"
        }]
}

非常感谢

1 个答案:

答案 0 :(得分:0)

如果目标是从JSON文件中返回第一级密钥,则可以通过引用数据数组所需的密钥来实现此目的。

if (!$mySearch) {
    echo 'No search';
} else {
    //I would need help here
    $temp = array($mySearch => $data[$mySearch]);
    //$temp is now an array with a key that is the key given by the user,
    //and the value of that key is the data from the $data variable

    header('Content-Type: application/json; charset=UTF-8');
    $json_string = json_encode($temp, JSON_PRETTY_PRINT);
    print $json_string;
}

需要记住的一点是,有人可能会提供一个在数据数组中不存在的密钥,这会引发错误。因此,请确保您的条件测试不仅是用户提供的密钥,而且还存在于您的数据中。

if (!$mySearch) {
    echo 'No search';
} elseif (empty($data[$mySearch])) {
    //Handle this error here
} else {
    ...
}