tags:

views:

17

answers:

1

All,

I have the following JSON Request that comes through a function call in PHP. As evident, each URL can belong to one or more catids.

How can I loop through the JSON request and create an associative array that denotes which catid has how many URLs in it.

Ex: $arr = array("140"=>3, "141"=>4, "144"=>3)

JSON Request:

 {
    "header": {
        "action": "loadurls"
    },
    "data": [
        {
            "url": "godaddy.com",
            "catids": [
                141 
            ] 
        },
        {
            "url": "cnn.com",
            "catids": [
                140 
            ] 
        },
        {
            "url": "zdnet.com",
            "catids": [
                140 
            ] 
        },
        {
            "url": "yahoo.com",
            "catids": [
                140,141,144 
            ] 
        },
        {
            "url": "google.com",
            "catids": [
                141,144 
            ] 
        },
        {
            "url": "rediff.com",
            "catids": [
                141 
            ] 
        },
        {
            "url": "apple.com",
            "catids": [
                144 
            ] 
        } 
    ] 
} 

Thanks

+1  A: 

This should do it:

var fooJson = {...jsonsnipped...};
var catCounts = new Object();
for(var i=0; i<fooJson.data.length; i++)
{
    var dataItem = fooJson.data[i];
    for(var j=0; j<dataItem.catids; j++)
    {
        var cat = dataItem.catids[j];
        if (catCounts[cat] >= 0)
        {
            catCounts[cat] = catCounts[cat] + 1;
        }
        else
        {
            catCounts[cat] = 1;
        }
    }
}

Note that I used a Object() instead of an Array() to store the counts. You want associative lookup by catid, you aren't actually storing a finite amount of items by index. If you used Array instead, you will get totally broken results from the .length property of the "Array", thus Object is more appropriate in this case. If you need to iterate the catids now, just use the for(var key in catCounts) syntax.

EDIT: This is intended to be javascript code, I realize now that perhaps you wanted PHP code. From what I remember of PHP, this should still work, but if not, it should be close.

David
This works great.. Thanks !
Vincent