Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a 2d array in a PHP file called $array, with the columns id, msg and timestamp

A multidimensional array is then created, and output as a JSON from an AJAX call:

$ok = 1;
$error = null;

echo JSON_ENCODE(array('ok'=>$ok, 'err'=>$error, 'arr'=>$array));

I am trying to loop through the nested array called arr, this I cannot figure out, what I have tried:

$.each(data,function(i,index){
    $('#msg_apnd').append(data[index].midt + data[index].msg);
});

This only loops through the data array, and therefore only the one row, when I need it to loop through the nested arr array, so i tried this:

$.each(data,function(i,index){
    $.each(i,function(i2,index2){
        $('#msg_apnd').append(arr[index].midt + arr[index].msg);
    });
});

I'm a little stuck and haven't been able to find a suitable answer elsewhere. I need the jQuery code to loop through the nested arr array in the AJAX response.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You can target the .arr using a member operator because data is an object

$.each(data.arr,function(idx, val){
        $('#msg_apnd').append(val.midt + val.msg);
});

Also $.each() callback receives the index of the current item as the first argument and the current item as the second argument

share|improve this answer

The success callback should be like below:

function (response) {
  console.log(response.ok, response.err, response.arr);
  $.each(response.arr, function(i, v){
    $('#msg_apnd').append(v.midt + v.msg);
  });
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.