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

后端 未结 4 1287
眼角桃花
眼角桃花 2020-12-13 15:40

Right now I have this PHP:

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

And this is sent through an AJAX GET request with JQuery

相关标签:
4条回答
  • 2020-12-13 16:13

    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
    }
    
    0 讨论(0)
  • 2020-12-13 16:15
      $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.....
    
    0 讨论(0)
  • 2020-12-13 16:16

    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];
    
    0 讨论(0)
  • 2020-12-13 16:27

    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
    
    0 讨论(0)
提交回复
热议问题