-1

Here is my code which is retrieving from db... and i stored that column values in array() variable...

$res1 = array();
while ($row = mysql_fetch_assoc($res)) {
    $res1[$i] = $row['address'];
    $i = $i + 1;
}

print_r($res1);

But problem is wen am trying to print this array it is printing as below:

"Array ( [0] => ameerpet [1] => panjagutta )"

but i need to print that array as below so that i can store in js variable for further using......

["ameerpet", "panjagutta"];
Arturs
  • 1,258
  • 5
  • 21
  • 28
Sweety Mouni
  • 51
  • 1
  • 2
  • 9

2 Answers2

1

Use json_encode() to encode your array to JSON format:

$json = json_encode($res1);

You can use that variable in JavaScript and use then use JSON.parse():

json = <?php echo $json; ?>
var obj = JSON.parse(json);
// obj now contains the array

Documentation: JSON.parse()

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • it is working but no need of json.parse....because if i use json.parse it is not accepting but wen i use direct var obj= it is accepting... – Sweety Mouni Aug 28 '13 at 10:32
0

Add this line where you want to declare the js array variable.

echo "var js_array = ". json_encode($res1) . ";\n";
rgin
  • 2,291
  • 4
  • 24
  • 32