PHP – 使用AND条件查询JSON文件

huangapple go评论60阅读模式
英文:

PHP - make query to JSON file with AND condition

问题

你的PHP代码中有一个小错误,导致了重复的结果。在处理number参数时,你使用了strpos函数,但number应该是一个整数,而不是一个字符串,所以这里需要使用==而不是strpos来进行比较。以下是修复后的代码:

// check value in number
if(isset($number)){
    if ($data[$i]->number == $number) {
        array_push($results, $data[$i]);
    } 
}

通过这个更正,你应该能够获得正确的结果,不再出现重复的条目。

英文:

I’m trying to query some data from a JSON file with PHP, i want to get objects based on string and number.

Here’s my 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"
    }
]

Here’s my query-user.php script:

<?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);
?>

On my browser, I call the following url:

http://example.com/users/query-user.php?string=doe&number=2

Here’s what I get as result:

[ 
{ "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" }
 ]

As you can see, I get the object with ID PMuKM818 twice, while I should get it once, together with the first object.

What am I doing wrong in my php code?

答案1

得分: 1

以下是翻译好的部分:

For quick answer you just need to use: https://www.php.net/manual/en/function.array-column

What is fastest way to process json objects.

UPDATE:

for full your code correct please use: https://www.php.net/manual/en/function.array-search

combinate with array_column, what way you will search more faster then one by one.

英文:

For quick answer you just need to use: https://www.php.net/manual/en/function.array-column

What is fastest way to process json objects.

UPDATE:

for full your code correct please use: https://www.php.net/manual/en/function.array-search

combinate with array_column, what way you will search more faster then one by one.

答案2

得分: 1

The object with the ID PMuKM818 corresponds to both of your query parameters: it contains Doe and also has the number 2.

如果您要防止这种情况发生,可以使用 if else 语句来设置筛选器的优先顺序,而不是简单的 if,或者在添加元素之前,在结果数组中添加现有的 ID 检查。

附加编辑

这不是最优雅的解决方案,但它可以满足您的需求:

foreach ($data as $details) {

    // check value in string
    if(isset($string)){
        if (strpos($details->string, $string) !== false) {
            $results[$details->id] = $details;
        }
    }

    // check element in array
    if(isset($aArray)){
        if (in_array($aArray, $details->aArray)) {
            $results[$details->id] = $details;
        } 
    }

    // check value in number
    if(isset($number)){
        if (strpos($details->number, $number) !== false) {
            $results[$details->id] = $details;
        } 
    }

    // check value in bool
    if(isset($bool)){
        if ($details->bool == $bool) {
            $results[$details->id] = $details;
        }
    }

}// ./ for

echo json_encode(array_values($results), JSON_PRETTY_PRINT);

我还将 for 循环替换为 foreach,但这不应影响结果。

英文:

The object with the ID PMuKM818 corresponds to both of your query parameters: it contains Doe and also has the number 2.

If you want to prevent that, either set an order of precedence for your filters using if else statements instead of simple if, or add a check for existing ids in the resulting array before adding the element.

ADDITIONAL EDIT

Not the most elegant solution but it does what you need:

foreach ($data as $details) {

    // check value in string
    if(isset($string)){
        if (strpos($details->string, $string) !== false) {
            $results[$details->id] = $details;
        }
    }

    // check element in array
    if(isset($aArray)){
        if (in_array($aArray, $details->aArray)) {
            $results[$details->id] = $details;
        } 
    }

    // check value in number
    if(isset($number)){
        if (strpos($details->number, $number) !== false) {
            $results[$details->id] = $details;
        } 
    }

    // check value in bool
    if(isset($bool)){
        if ($details->bool == $bool) {
            $results[$details->id] = $details;
        }
    }

}// ./ for

echo json_encode(array_values($results), JSON_PRETTY_PRINT);

I've also replaced the for loop with a foreach, but that should not impact on the result

huangapple
  • 本文由 发表于 2020年1月6日 21:29:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定