php - PHP - 使用 AND 条件查询 JSON 文件
问题描述
我正在尝试使用 PHP 从 JSON 文件中查询一些数据,我想获取基于string
and的对象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" }
]
如您所见,我PMuKM818
两次获得具有 ID 的对象,而我应该获得一次,连同第一个对象。
我在我的 php 代码中做错了什么?
解决方案
为了快速回答你只需要使用:https ://www.php.net/manual/en/function.array-column
什么是处理 json 对象的最快方法。
更新:
完整的代码正确请使用:https ://www.php.net/manual/en/function.array-search
与 array_column 结合,你会以什么方式搜索得更快然后一个一个。
推荐阅读
- airflow - 气流 - 如何根据运营商结果发送电子邮件?
- c# - Hangfire - redis 服务器密钥
- jquery - 修剪字符串宽度jQuery
- laravel - 如何使用 Eloqument ORM 方法和模型的 halp 进行相同的 SQL 查询
- java - Oracle 阵列和休眠
- android - 在 DialogFragment 中更改布局时出现 IllegalStateException
- php - Php/Jquery 在循环数据时添加行
- java - 从具有不同高度的表格行中提取 pdf 文本(使用 pdfbox 库的 java)
- https - 生成主密钥 tls1.2
- python - 使用 Open CV 屏蔽水平线和垂直线