简体   繁体   中英

Returning two-dimensional array from PHP to JavaScript

My JavaScript calls a PHP script that builds a two-dimensional array of the folders on a disk. The folder name, number of files, and total size is included in the array, so the array looks like:

folders[$i][0] = $folder_name;
folders[$i][1] = $files_in_folder;
folders[$i][2] = $folder_size;

The call is made from JavaScript with:

$.post('myajax.php', {op : get_folders'},       
                           function(responseTxt, statusTxt, xhr) {  
                           });

What is the best way to have PHP return the array, and the best way for JavaScript, or jQuery, to get it back into a two dimensional array for easy access?

Thanks

JSON is a good approach as it's a de-facto standard for structuring data in JavaScript. A PHP array can be used to generate JSON with json_encode() .

Using JSON API best practices, here is how I would structure the JSON response:

{folders: [
 {name: 'Folder name', size: 513, numberOfFiles: 7},
 {name: 'Another folder', size: 1214, numberOfFiles: 34},
 etc...
]} 

The code in myajax.php would be along the lines of:

<?php
$folderItems = array();

foreach($folders as $folder) {
  array_push($folderItems, array(
    "name" => $folder[0],
    "numberOfFiles" => $folder[1],
    "size" => $folder[2]
  ));  
}

echo json_encode(array("folders" => $folderItems));
?>

The jQuery code used to collect the data is then:

jQuery.getJSON('/myajax.php', function(data){
  var folders = data.folders;
  // Your code here...
});

short answer:

json_decode($string)

and

json_encode($array)

Whether the array is two-dimensional or one-dimensional, using the json_encode , a built-in function of PHP as of v5.2.0, just before sending it as the response is the best way to prepare it for easy use in JavaScript.

This way, the Ajax call receives a JSON object, which is naturally easy to reference or iterate through in JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM