【发布时间】:2023-03-06 21:04:01
【问题描述】:
我正在尝试使用 PHP 从 JSON 文件中查询一些数据,我想获取基于 string 和 number 的对象。
这是我的 JSON:
[
{
"id": "5V28tqJ1",
"string": "john doe",
"number": 1,
"aArray": [
"cc",
"kk",
"lo",
"mm"
],
"bool": false,
"createdAt": "2020-01-02T15:16:11",
"updatedAt": "2020-01-05T19:37:02"
},
{
"id": "PMuKM818",
"string": "sarah doe",
"number": 2,
"aArray": [
"bb",
"cc"
],
"bool": true,
"createdAt": "2020-01-02T16:16:23",
"updatedAt": "2020-01-05T19:37:14"
},
{
"id": "m8HSbEQe",
"string": "bob smith",
"number": 3,
"aArray": [
"dd",
"ee",
"ff"
],
"bool": false,
"createdAt": "2020-01-02T17:16:36",
"updatedAt": "2020-01-05T19:37:32"
}
]
这是我的query-user.php 脚本:
<?php include 'header.php';
$string = $_GET['string'];
$aArray = $_GET['aArray'];
$number = $_GET['number'];
$bool = $_GET['bool'];
$data = file_get_contents($className. '.json');
$data = json_decode($data);
$results = array();
for ($i=0; $i<count($data); $i++) {
// check value in string
if(isset($string)){
if (strpos($data[$i]->string, $string) !== false) {
array_push($results, $data[$i]);
}
}
// check element in array
if(isset($aArray)){
if (in_array($aArray, $data[$i]->aArray)) {
array_push($results, $data[$i]);
}
}
// check value in number
if(isset($number)){
if (strpos($data[$i]->number, $number) !== false) {
array_push($results, $data[$i]);
}
}
// check value in bool
if(isset($bool)){
if ($data[$i]->bool == $bool) {
array_push($results, $data[$i]);
}
}
}// ./ for
echo json_encode($results, JSON_PRETTY_PRINT);
?>
在我的浏览器上,我调用以下网址:
http://example.com/users/query-user.php?string=doe&number=2
这是我得到的结果:
[
{ "id": "5V28tqJ1", "string": "john doe", "number": 1, "aArray": [ "cc", "kk", "lo", "mm" ], "bool": false, "createdAt": "2020-01-02T15:16:11", "updatedAt": "2020-01-05T19:37:02" },
{ "id": "PMuKM818", "string": "sarah doe", "number": 2, "aArray": [ "bb", "cc" ], "bool": true, "createdAt": "2020-01-02T16:16:23", "updatedAt": "2020-01-05T19:37:14" },
{ "id": "PMuKM818", "string": "sarah doe", "number": 2, "aArray": [ "bb", "cc" ], "bool": true, "createdAt": "2020-01-02T16:16:23", "updatedAt": "2020-01-05T19:37:14" }
]
如你所见,我得到了 ID 为 PMuKM818 的对象两次,而我应该得到一次,连同第一个对象。
我在我的 php 代码中做错了什么?
【问题讨论】: