Php 通过解析url中的数组名称,从JSON文件获取数组
我有这个JSON文件: alldata.jsonPhp 通过解析url中的数组名称,从JSON文件获取数组,php,json,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": [ {
{
"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)时,例如“”,我只会得到“players”数组。另外,如果我解析文件中的其他数组名,它将只给出该数组。下面是我的意思的一个例子:
{
"players": [
{
"name": "Marcos Alonso",
"position": "Left-Back",
"nationality": "Spain",
"marketValue": "9,000,000 €",
"created": "2017-04-15 10:04:58"
}]
}
非常感谢如果目标是从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 {
...
}