Multidimensional Array (array of array)

i am trying to create multidimensional array…For right now I have this…

  var a = []; // array of size 0  
  a[0] = [];
  a[1] = []

Is there any better way to do this? I do not know the size of array until run time. So right now i know that I have 2 arrays of array but sometimes i will have more depending how many rows I pull out from database.

a = [[] []]

Note that // array of size 0 is correct, but is not a limiter. You dont need to know how big the array is going to be before constructing it.
If you dont know how many records there will be, then your loop will simply invoke
a.push(newitem)
for each item.

What I am trying to do is this…

I have function in PHP that does some work with database pulls out records based on query. Results of what query when printer with print_r function look like this…

Array ( [0] => Array ( [my_id] => 5 [name] => Robert ) [1] => Array ( [my_id] => 6 [name] => John ) ) 

I pass this array to JS external file. As you can see from above right now that array has 2 records but sometimes it might have 5 or 6 or whatever. Right now I am accessing this records like this…

myArray[0].my_id;
myArray[0].name;

Investigate [fphp]json_encode[/fphp]. It’ll take care of all of that for you.

var a = <?php echo json_encode($my_database_results_array) ?>;

Yes i tried that but it didnt really work for me so I had to try something else for now.

My post re JSON

I tried it this way and this seems to work and allowed me to dynamically create array based on array size i pass in from my PHP code…

  var  a = new Array(phpArray.length);
 
  for (var j = 0 ; j < a.length ; j++ ) {
    a[j] = new Array();
  }

I don’t know if there is a “best” way, but here is what I do.

var a = [];  // no need to size initially; keep code small and fast-loading
var M, N; // number of rows and columns of array, respectively

If you could feed in values for M and N, that would be good. Saving them as their own variables might be handy for future use. Or you could calculate them on the fly. Personally, I like to avoid computing anything repeatedly, especially within loops, so once values are calculated I save them. Perhaps you could assign M = phpArray.length. N could also be computed at run-time. Either way, once you have values for the number of rows (M) and columns (N) of the array to be made, resize the array as needed.

for (var i = 0; i < M; ++i) { // Create M new arrays within the existing array
   a[i] = [];
   for (var j = 0; j < N; ++j) {
     a[i][j] = value to be assigned;
   }
 }

Voila! That is one way to dynamically create a 2-dimensional array in JavaScript. All it takes is two loops.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.