I need some help with parsing and looking through JSON result with PHP. Within the example result below, I need to check against the categories of the technology.
The outcome I would expect is that if the category analytics has been found, to flag this with a true variable, and also to set the variable with the name of the analytics, for example “google analytics”
This is the example code
foreach ($resp['technologies'] as $item) { if ($item['categories'][0] === 'analytics') { $found = true; $analyticsis= $item['name'];
This is the example JSON we are looking through.
[{ "url": "https://www.websiteexample.co.uk", "technologies": [{ "slug": "google-analytics", "name": "Google Analytics", "versions": [], "trafficRank": 0, "categories": [{ "id": 10, "slug": "analytics", "name": "Analytics" }, { "id": 61, "slug": "saas", "name": "SaaS" } ] }
Advertisement
Answer
First of all, json
is a string.
If you have json, it should be parsed:
$data = json_decode($json, true);
If your “json” is an array, it is not a json, it is an array.
Search
Just traverse into you structure and when you found what you looking for, stop and save all necessary data:
$json = <<<'JSON' [{ "url": "https://www.websiteexample.co.uk", "technologies": [{ "slug": "google-analytics", "name": "Google Analytics", "categories": [ {"id": 10, "slug": "analytics", "name": "Analytics"}, {"id": 61, "slug": "saas", "name": "SaaS"} ] }] }] JSON; $data = json_decode($json, true); $needle = 'analytics'; $foundTech = null; $foundCategory = null; foreach ($data as $resp) { foreach ($resp['technologies'] as $tech) { foreach ($tech['categories'] as $category) { if ($category['slug'] === $needle) { $foundTech = $tech; $foundCategory = $category; break 3; } } } } if ($foundCategory) { echo $foundTech['name'], PHP_EOL; echo $foundCategory['name'], PHP_EOL; }
Google Analytics Analytics
If you need more than one search in that structure it would be wise to create some maps/indices before.