Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Search JSON for value

Tags:

json

php

So I have a json object which has a structure like so:

{
"John Doe": [
    {
        "childName": "Harry",
        "childAge": 15,
        "childGender": "Male"
    },
    {
        "childName": "Sally",
        "childAge": 9,
        "childGender": "Female"
    },
],
"Miss Piggy": [
    {
        "childName": "Jane",
        "childAge": 20,
        "childGender": "Female"
    }
],

}

What I want to do is be able to make a query for the childName, childAge, or childGender, and return that sub-object if it's found.

For example:

searchJson($jsonObj, 'childName', 'Sally') // returns {"childName":"Sally", "childAge":9,"childGender":"Female"}

What would be the best method at going at this?

like image 613
Baehr Avatar asked Jan 01 '12 01:01

Baehr


People also ask

How to get nested JSON value in PHP?

Firstly read the contents of the text file into a string variable using the file_get_contents() function and then use json_decode() function to convert the JSON string to a PHP variable. $filepath = './persons. txt'; $json_string = file_get_contents($filepath); $json = json_decode($json_string, true);

Does JSON work with PHP?

PHP has some built-in functions to handle JSON. First, we will look at the following two functions: json_encode() json_decode()

What is JSON array in PHP?

A JSON array is produced by assigning a contiguous integer-indexed PHP array into a JSON domain tree path. A PHP array variable is contiguous integer-indexed if it contains only integer keys that are sequenced from 0 to n -1 (where n is the total number of items in the array).


1 Answers

function searchJson($obj, $field, $value) {
    foreach($obj as $item) {
        foreach($item as $child) {
            if(isset($child->$field) && $child->$field == $value) {
                return $child;
            }
        }
    }
    return null;
}
like image 129
Tim Cooper Avatar answered Oct 02 '22 19:10

Tim Cooper