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?
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);
PHP has some built-in functions to handle JSON. First, we will look at the following two functions: json_encode() json_decode()
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).
function searchJson($obj, $field, $value) {
foreach($obj as $item) {
foreach($item as $child) {
if(isset($child->$field) && $child->$field == $value) {
return $child;
}
}
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With