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

后端 未结 4 1295
眼角桃花
眼角桃花 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
    }
    

提交回复
热议问题