我正在尝试制作一个简单的JSON检索器。
这就是我正在尝试做的事情。 例如当我输入 日本。我将数据发布到php。 我希望它加载它拥有的json并搜索包含该国家(日本)的值的数组
将仅包含包含该值的结果的较小的缩减json数组发送回页面。
关键是国家/地区, 示例json
{
"1": {
"country": "America",
"Name": "Harry",
"Age": "41"
},
"2": {
"country": "America",
"Name": "ben",
"Age": "40"
},
"3": {
"country": "Japan",
"Name": "taka",
"Age": "48"
},
"4": {
"country": "Japan",
"Name": "John",
"Age": "41"
},
"5": {
"country": "America",
"Name": "Ted",
"Age": "41"
},
"6": {
"country": "America",
"Name": "Simon",
"Age": "41"
}
}
var country = $(".country").val();
$.ajax ({
url: json.php,
type: 'POST',
data: {
'find': country,
},
success: function (results) {
console.log(results);
},
fail: function(data) {
console.log( data.responseText );
console.log( 'Request Failed' + data.statusText );
}
})
<input name="country" class="country" type="text" placeholder="type country"></input>
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$jsonurl = "data.json";
$json = file_get_contents($jsonurl);
$find = $_POST["find"];
$decode = json_decode($json, true);
$results = array_filter($decode[''], function($country) {
return $country['country'] == $find;
});
var_dump($results);
任何帮助将不胜感激...
答案 0 :(得分:0)
这是您可以满足要求的代码示例。
$my_json = '{
"1": {"country": "America","Name": "Harry","Age": "41"},
"2": {"country": "America","Name": "ben","Age": "40"},
"3": {"country": "Japan","Name": "taka","Age": "48"},
"4": {"country": "Japan","Name": "John","Age": "41"},
"5": {"country": "America","Name": "Ted","Age": "41"},
"6": {"country": "America","Name": "Simon","Age": "41"}
}';
$json_arr = json_decode($my_json);
$item = array();
foreach($j as $k=>$struct) {
if ('Japan' == $struct->country) {
$item[$k] = $struct;
}
}
echo 'Object Array form::';
echo '---------------------------';
print_r(array_values($item));
echo 'Json form::';
echo '---------------------------';
echo json_encode(array_values($item));