Skip to content Skip to sidebar Skip to footer

How To Convert Json To Array And Loop Over It In Jquery?

I am using JSON to communicate with the user. PHP converts array to JSON to this form: {'success':'text-to-display','warning':'NONE','notice':'text-to-display','error':'NONE'} j

Solution 1:

OK let's say we have a PHP array

PHP:

<?php$myArray = array(
    "test1"=>array("name"=>"test1name", "value"=>"test1value"),
    "test2"=>array("name"=>"test2name", "value"=>"test2value"),
    "test3"=>array("name"=>"test3name", "value"=>"test3value")
);

// Now make a javascript variable containing echoed JSONecho"<script type='text/javascript'>var returnedJSON = " . json_encode($myArray) . ";</script>";

This will output the below JSON giving you a javascript object:

var returnedJSON = {"test1":{"name":"test1name","value":"test1value"},"test2":{"name":"test2name","value":"test2value"},"test3":{"name":"test3name","value":"test3value"}};

Javascript:

//Once you have the variable from above which can come in various ways (through ajax, jsonp etc) you can iterate over it quite simply in jQuery
$.each(returnedJSON, function (index, value) {
    console.log(index + ": " + value.name);
});

http://api.jquery.com/jquery.each/

Demo http://jsfiddle.net/robschmuecker/HqarE/1/

Solution 2:

Rather than this:

$uwaga = array();
$uwaga[1] = array('type' => 'notice', 'text' => 'old statement');
$uwaga[2] = array('type' => 'notice', 'text' => 'new statement');

Just do this, without indices:

$uwaga = array();
$uwaga[] = array('type' => 'notice', 'text' => 'old statement');
$uwaga[] = array('type' => 'notice', 'text' => 'new statement');

That will assign them indices (from zero, not one) at the end of the array.

Then take all of these:

if(data.notice !== 'NONE'){
    displayNotice(data.notice);
}
if(data.success !== 'NONE'){
    displaySuccess(data.success);
}
if(data.warning !== 'NONE'){
    displayWarning(data.warning);
}
if(data.error !== 'NONE'){
    displayError(data.error);
}

... and wrap them in a block of jQuery's each() as Rob recommends. It will then become (assuming the data is in json.messages):

$.each(json.messages, function (index, data) {
    if(data.notice !== 'NONE'){
        displayNotice(data.notice);
    }
    if(data.success !== 'NONE'){
        displaySuccess(data.success);
    }
    if(data.warning !== 'NONE'){
        displayWarning(data.warning);
    }
    if(data.error !== 'NONE'){
        displayError(data.error);
    }
});

Post a Comment for "How To Convert Json To Array And Loop Over It In Jquery?"