How to Search for Data in JSON using PHP
  John Mwaniki /   13 Dec 2023

How to Search for Data in JSON using PHP

While SQL is used for querying data in relational databases (such as MySQL), searching for specific information within JSON strings presents a different challenge.

Though JSON can be used to store similar data as a relational db table, it has a different format, whose querying requires a different approach.

In this guide, I'll show you how to effectively search for specific data in JSON using PHP with multiple examples.

JSON consists of key-value pairs, arrays, and objects. The pairs are separated by commas and each consists of a key (in double quotes), followed by a colon, and then a value (string, number, JSON object, array, boolean, or null). The objects are surrounded by curly braces {} and arrays by square brackets [].

To access data stored in a JSON file in PHP, we use the file_get_contents() function with the file path as its argument.

$jsondata = file_get_contents("path/to/file.json");

When receiving JSON data from a POST request in PHP, we use the file_get_contents() function with the string "php://input" as its argument.

$jsondata = file_get_contents("php://input");

In PHP, JSON data is decoded into arrays for manipulation.

Example

$jsonData = '{"name": "John Doe", "age": 30, "city": "New York"}';
$decodedData = json_decode($jsonData, true);
print_r($decodedData);

Output
Array ( [name] => John Doe [age] => 30 [city] => New York )

Searching for JSON Data using PHP

For demonstrations, we will use the JSON data below stored in a file named "users.json" located in the same directory as the PHP script. It comprises a "users" object, which is an array containing five objects where each object is a record of a user comprising their details.

{
"users":[
{"id":"1","name":"John Doe","email":"john@gmail.com","age":"30","country":"Spain"},
{"id":"2","name":"Muhamad Farah","email":"muhamad@gmail.com","age":"35","country":"Egypt"},
{"id":"3","name":"Jane Davidson","email":"jane@gmail.com","age":"27","country":"USA"},
{"id":"4","name":"Rajesh Kumar","email":"rajesh@yahoo.com","age":"25","country":"India"},
{"id":"5","name":"Philip Omondi","email":"philip@email.com","age":"32","country":"Kenya"}
]
}

We will return one or multiple records based on the search parameters.

Example 1: Searching for a user record using a unique key

If the users' JSON object comprises an array of objects with unique values for a certain key, such as the ID or email like in our example, we can use it to fetch a specific object.

An equivalent of the SQL query;

SELECT * FROM users WHERE id = '$id';

<?php
$json = file_get_contents('users.json');
$decoded = json_decode($json, true);
$users = $decoded["users"];

$id = 3;

foreach ($users as $user) {
    if ($user["id"] == $id) {
        $result = $user;
        break;
    }
}

if(isset($result)){
    // Returning result as an array
    print_r($result);
    echo "<br><br>";

    // Returning result as a JSON string
    echo json_encode($result);
    echo "<br><br>";

    // Displaying individual values of result
    echo "ID: ".$result["id"]."<br>";
    echo "Name: ".$result["name"]."<br>";
    echo "Email: ".$result["email"]."<br>";
    echo "Age: ".$result["age"]."<br>";
    echo "country: ".$result["country"];
}
else{
    echo "Record not found";
}
?>

Output
Array ( [id] => 3 [name] => Jane Davidson [email] => jane@gmail.com [age] => 27 [country] => USA )

{"id":"3","name":"Jane Davidson","email":"jane@gmail.com","age":"27","country":"USA"}

ID: 3
Name: Jane Davidson
Email: jane@gmail.com
Age: 27
country: USA

In this example, we accessed the content of the "users.json" file, decoded it to an array, and accessed the value of the "users" object, which comprises five associative arrays. We then iterated through them using the foreach() loop, checking and comparing the value of the "id" element with that of the $id we were searching for using the comparison (==) operator.

If the two IDs match, we get the current element (array), store it in the $result variable, and break the loop as we have already found what we were looking for.

Outside of the loop, we use the isset() function to check whether the $result variable has been set and use its value as we wish.

If we wanted to search by email where email is unique for each record, we would need to replace if ($user["id"] == $id) { with if ($user["email"] == $email) {.

Example 2: Searching for multiple records

In some cases, multiple records will match your search parameters. For example, in our JSON string, each user has a different age, and their ages range between 25 and 35 years.

We want to return the user details where age is greater than or equal to 30 years.

<?php
$json = file_get_contents('users.json');
$decoded = json_decode($json, true);
$users = $decoded["users"];

$result = array();
foreach ($users as $user) {
    if ($user["age"] >= 30) {
        $result[] = $user;
    }
}


// Displaying result as an array
print_r($result);
echo "<br><br>";

// Displaying result as a JSON string
echo json_encode($result);
?>

Output
Array (
[0] => Array ( [id] => 1 [name] => John Doe [email] => john@gmail.com [age] => 30 [country] => Spain )
[1] => Array ( [id] => 2 [name] => Muhamad Farah [email] => muhamad@gmail.com [age] => 35 [country] => Egypt )
[2] => Array ( [id] => 5 [name] => Philip Omondi [email] => philip@email.com [age] => 32 [country] => Kenya )
)

[{"id":"1","name":"John Doe","email":"john@gmail.com","age":"30","country":"Spain"},
{"id":"2","name":"Muhamad Farah","email":"muhamad@gmail.com","age":"35","country":"Egypt"},
{"id":"5","name":"Philip Omondi","email":"philip@email.com","age":"32","country":"Kenya"}]

Example 3: Searching for records that contain a certain phrase

You may want to search and return the objects/records whose certain key-value pair contains a specific character, word, or phrase.

<?php
$json = file_get_contents('users.json');
$decoded = json_decode($json, true);
$users = $decoded["users"];

$searchword = "david";
$result = array();
foreach ($users as $user) {
    if(stripos($user["name"], $searchword) !== false){
        $result[] = $user;
    }
}


// Displaying result as an array
print_r($result);
echo "<br><br>";

// Displaying result as a JSON string
echo json_encode($result);
?>

Output
Array ( [0] => Array ( [id] => 3 [name] => Jane Davidson [email] => jane@gmail.com [age] => 27 [country] => USA ) )

[{"id":"3","name":"Jane Davidson","email":"jane@gmail.com","age":"27","country":"USA"}]

In this example, we have searched for records where the user's name contains the term "david". You can search any array element with any term within the array.

That's it!

Now you can search and extract information from JSON strings in PHP.