tags:

views:

65

answers:

2

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

+5  A: 

Try the built-in json_decode function.

Matchu
+6  A: 

What about something like this :


You first use json_decode, which is php's built-in function to decode JSON data :

$json = '{
    ...
}';
$data = json_decode($json);

Here, you can seen what PHP kind of data (i.e. objects, arrays, ...) the decoding of the JSON string gave you, using, for example :

var_dump($data);


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 :

$catId = 30;
$urls = array();
foreach ($data->jsondata as $d) {
    if (in_array($catId, $d->categoryid)) {
        $urls[] = $d->url;
    }
}

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 :

var_dump($urls);

Gives you, in this example :

array
  0 => string 'www.cnn.com' (length=11)
  1 => string 'www.time.com' (length=12)
  2 => string 'www.microsoft.com' (length=17)
  3 => string 'www.freshmeat.com' (length=17)


Up to you to build from this -- there shouldn't be much left to do ;-)

Pascal MARTIN