jay
jay

Reputation: 10325

PHP json_encode results and jQuery

I'm trying to take a jSON encoded string out of my database and loop through the items but I'm having some difficulty. Here's the string in the database:

["volunteers","seat_dedication_program","memberships"]

And here is the code:

//Looks for _checkbox when looping through my database fields (object dbVals) and turns it into a true jQuery array if it finds it.
if( key.search(/_checkbox/i) > 0 ) var arr = $.makeArray(dbVals[key]);

//If it is an array, loop through the array values and show them
if($.isArray(arr)==true){
    $.each(arr, function(i, n){
        alert(i + " : " + n);
    });
}

What I want is this:

//alert
0 : volunteers
//alert
1 : seat_dedication_program etc...

What I'm getting is this:

//alert
0 : ["volunteers","seat_dedication_program","memberships"]

I think I've included all relevant data. Can anyone help me figure out why this is happening?

Thanks.

Upvotes: 0

Views: 2745

Answers (2)

slebetman
slebetman

Reputation: 113866

Just use a regular for loop:

for (var i=0; i<arr.length; i++) {
    var n = arr[i];
    alert(i + " : " + n);
}

or for large arrays, the slightly optimized:

for (var i=0,l=arr.length; i<l; i++) {
    var n = arr[i];
    alert(i + " : " + n);
}

or if you really hate for loops:

Array.prototype.each = function (callback) {
    for (var index=0,l=this.length;index<l;index++) {
        var item = this[index];

        // index is second arg since it's optional
        callback(item,index);
    }
}

arr.each(function(n,i){
    alert(i + " : " + n);
});

but I'd recommend the for loop to avoid clashing with library modifications or when Firefox suddenly decide to implement its own each method for arrays (some libraries have already been bitten by this).

Upvotes: 0

Carl
Carl

Reputation: 1263

Using $.makeArray(..) is giving you an array where the only element is the string you gave it. You need to parse the string into a JavaScript object. Use the JSON2.js library to parse then your code would look something like this.

var arr = JSON.parse(dbVals[key]);

if($.isArray(arr)==true){
    $.each(arr, function(i, n){
        alert(i + " : " + n);
    });
}

Upvotes: 1

Related Questions