2017-04-18 39 views
0

我有這個JSON文件解析數組名獲得從JSON文件數組:通過在URL

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" 
     }] 
} 

非常感謝

回答

0

如果目標是剛剛從你的JSON文件回到1級關鍵,那麼你可以通過引用您需要的關鍵做到這一點數據的數組。

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 { 
    ... 
}