views:

203

answers:

3

Ok, what i'm trying to do here is to pass a 2d array from php to javascript in the easiest way possible. The main reason for this is because i have the array which is previously filled with data via the phpscript and doing it one by one and just "calling it as it's needed" will not work out too well since well there's more than just one row required when it's called and i'd rather not do something like for all of the elements in it as it's number is unknown until it gets said data from the database. I was going to do a while loop to write in some of the data into elements sot hat it coudl be later pulled up more easily but i cannot seem to find an easy way to do this currently.

If anyone has an easy way to transfer this to javascript without having to do what i previously said.

+11  A: 

As a JSON Object using the json_encode function. You can then read this with Javascript easily as it is a native javascript object. http://php.net/manual/en/function.json-encode.php

json_encode($array);

JSON is easily parsable in JQuery, but for pure JavaScript see here:

http://www.json.org/js.html

Gazler
A: 

Lazy method:

<script>
var arr = [];

<?php
    $phparray = array(array(1, 2, 3), array(4, 5, 6));

    foreach ($phparray as $i) {
        echo 'arr.push([' . implode(', ', $i) . ']);';
    }
?>

</script>

This isn't the "best" method, but hey it works.

Alex
A: 

hi, thanks for the code. I tried it but its only working on numbers.If I try to use character array or string array, it fails.

Hafsa