Steve
Steve

Reputation: 4898

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

Upvotes: 0

Views: 107

Answers (3)

Pete
Pete

Reputation: 2246

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...
});

Upvotes: 1

Manmaru
Manmaru

Reputation: 578

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.

Upvotes: 0

dynamic
dynamic

Reputation: 48101

short answer:

json_decode($string)

and

json_encode($array)

Upvotes: 0

Related Questions