6

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?

1 Answer 1

17
function searchJson($obj, $field, $value) {
    foreach($obj as $item) {
        foreach($item as $child) {
            if(isset($child->$field) && $child->$field == $value) {
                return $child;
            }
        }
    }
    return null;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@JosephSilber: $obj is a stdClass object, which would be the result of json_decode().
Is there a way to do it without looping through everything? E.g. returning json as an associative array and then using array_ functions to get what you need?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.