首页 > 解决方案 > PHP - 使用 AND 条件查询 JSON 文件

问题描述

我正在尝试使用 PHP 从 JSON 文件中查询一些数据,我想获取基于stringand的对象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 代码中做错了什么?

标签: phparraysjsonstring

解决方案


为了快速回答你只需要使用:https ://www.php.net/manual/en/function.array-column

什么是处理 json 对象的最快方法。

更新:

完整的代码正确请使用:https ://www.php.net/manual/en/function.array-search

与 array_column 结合,你会以什么方式搜索得更快然后一个一个。


推荐阅读