PHP search JSON for value

So, I have a json object that has this structure:

{ "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 make a request for childName, childAge or childGender and return this sub-object if it is found.

For example:

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

What would be the best method for doing this?

+7
source share
1 answer
 function searchJson($obj, $field, $value) { foreach($obj as $item) { foreach($item as $child) { if(isset($child->$field) && $child->$field == $value) { return $child; } } } return null; } 
+18
source

All Articles