Baehr
Baehr

Reputation: 686

PHP Search JSON for value

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?

Upvotes: 6

Views: 13048

Answers (1)

user142162
user142162

Reputation:

function searchJson($obj, $field, $value) {
    foreach($obj as $item) {
        foreach($item as $child) {
            if(isset($child->$field) && $child->$field == $value) {
                return $child;
            }
        }
    }
    return null;
}

Upvotes: 17

Related Questions