All,
I have the following JSON Data. I need help writing a function in PHP which takes a categoryid and returns all URLs belonging to it in an array.
Something like this::
<?php
function returnCategoryURLs(catId)
{
//Parse the JSON data here..
return URLArray;
}
?>
{
"jsondata": [
{
"categoryid": [
20
],
"url": "www.google.com"
},
{
"categoryid": [
20
],
"url": "www.yahoo.com"
},
{
"categoryid": [
30
],
"url": "www.cnn.com"
},
{
"categoryid": [
30
],
"url": "www.time.com"
},
{
"categoryid": [
5,
6,
30
],
"url": "www.microsoft.com"
},
{
"categoryid": [
30
],
"url": "www.freshmeat.com"
}
]
}
Thanks
What about something like this :
You first use
json_decode
, which is php's built-in function to decode JSON data :Here, you can seen what PHP kind of data (i.e. objects, arrays, ...) the decoding of the JSON string gave you, using, for example :
And, then, you loop over the data items, searching in each element's
categoryid
if the$catId
you are searching for is in the list --in_array
helps doing that :And, each time you find a match, add the
url
to an array...Which means that, at the end of the loop, you have the list of URLs :
Gives you, in this example :
Up to you to build from this -- there shouldn't be much left to do ;-)