Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass multiple arrays to PHP json_encode and parse it with jQuery?

Right now I have this PHP:

$columns = array(*/Data*/);
echo json_encode($columns);

And this is sent through an AJAX GET request with JQuery.

var columns = jQuery.parseJSON(response);

I would like to be able to send more than one array in the json_encode() is there any way to do this and how would you parse it with jQuery?

like image 331
chromedude Avatar asked Dec 04 '11 04:12

chromedude


4 Answers

Sure, you could send an array of array. PHP associative array will become a javascript object.

In PHP:

$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
echo json_encode($data);

and then on jQuery

var data = jQuery.parseJSON(response);

then you could then do something like this to access the values

console.log(data.fruits[0]); // apple
console.log(data.animals[1]); // elephant
like image 53
Andronicus Avatar answered Oct 06 '22 01:10

Andronicus


The code should be like the following:

$columns = array(/*Data*/);
$columns1 = array(/*Data1*/);
echo json_encode(array($columns,$columns1));

in jQuery use

var columns_array=jQuery.parseJSON(response);
columns=columns_array[0];
columns1=columns_array[1];
like image 22
zb' Avatar answered Oct 06 '22 03:10

zb'


  $data1 = array();
  $data2 = array();
  $data1[] = array('apple','banana','cherry');
  $data2[] = array('dog', 'elephant');
  echo json_encode(array($data1,$data2));

in ajax,

      console.log(response[0][0])//apple
      console.log(response[1][0])//dog.....
like image 20
learner Avatar answered Oct 06 '22 03:10

learner


After you have populated all the arrays namely $array1_json, $array2_json etc in my case,

$number_of_array1elements = count($array1_json);
$number_of_array2elements = count($array2_json);
$number_of_array3elements = count($array3_json);

array_unshift($array1_json , $number_of_array1elements); 
// pushes element to the start of array1_json
array_unshift($array2_json , $number_of_array2elements);
array_unshift($array3_json , $number_of_array3elements);

and similarly for other arrays.

echo json_encode( array_merge($array1_json, $array2_json, $array3_json) );

In your .js file, use:

var val = xmlhttp.responseText;
var jsonData = JSON.parse(val);
var number_of_array1elements = jsonData[0];
for (var i = 1; i <= number_of_array1elements; i++ ) 
{
    // use jsonData[i] to select the required element and do whatever is needed with it
}
var number_of_array2elements = jsonData[i];
for ( i = i+1; i <= number_of_array1elements+number_of_array2elements+1; i++ ) 
{
     // use jsonData[i] to select the required element and do whatever is needed with it
}
like image 38
uutsav Avatar answered Oct 06 '22 02:10

uutsav