所以我有一个json对象,其结构如下:
{ "John Doe": [ { "childName": "Harry","childAge": 15,"childGender": "Male" },{ "childName": "Sally","childAge": 9,"childGender": "Female" },],"Miss Piggy": [ { "childName": "Jane","childAge": 20,"childGender": "Female" } ],
}
我想要做的是能够查询childName,childAge或childGender,并返回该子对象(如果已找到).
例如:
searchJson($jsonObj,'childName','Sally') // returns {"childName":"Sally","childAge":9,"childGender":"Female"}
在这方面最好的方法是什么?
function searchJson($obj,$field,$value) { foreach($obj as $item) { foreach($item as $child) { if(isset($child->$field) && $child->$field == $value) { return $child; } } } return null; }