2

I followed this topic Convert array php to java , but it is not successful for me. My code:

<script>
    var dataobject=<?php
        $returnarry=getDataArray("Select product_id, product_name, product_price from product");


    echo json_encode(returnarry);
    ?>;
    //How to convert dataobject to  an array
</script> 

How to convert dataobject to an array

Cœur
  • 37,241
  • 25
  • 195
  • 267
Hoang
  • 35
  • 4

1 Answers1

-1

PHP function to convert PHP arrays into Javascript is json_encode() only.Note that json_encode() is available only in PHP 5.2 and up, so please check whther you're using an older version.

Ref: http://php.net/manual/en/function.json-encode.php

You can see the example in same page: Example #1 A json_encode() example

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

The above example will output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

For multi dimensional arrays use below one:

$arr = array();
while($row = mysql_fetch_assoc($returnarray)) {
$arr[] = $row; 
}
echo json_encode($arr);

Use it in javascript as:

<script type="text/javascript">

var jArray= <?php echo json_encode($arr); ?>;

for(var i=0;i<10;i++){ // use correct limit instead of 10
    alert(jArray[i]);
 }
</script>

Another way to get elements is: alert(jArray[0].Key);

Aajan
  • 927
  • 1
  • 10
  • 23
  • Thanks Aajan. I knew to process when array has one row. But how about multi rows when I select data from table in SQL ?. My Php is 5.5. – Hoang Feb 29 '16 at 09:26
  • Thanks Aajab. How can I use it in javascript. Can I convert it to array in Java Script, could you help me. – Hoang Feb 29 '16 at 10:01
  • 1
    I tested your code, I just modified a little, then it worked: $result = $conn->query($sql); $arr = array(); while($row = $result->fetch_assoc()) { $arr[] = $row; } // var_dump($arr); echo json_encode($arr); In alert method, I put property of object :alert (jArray[i].Product_code) – Hoang Mar 01 '16 at 03:28
  • Thanks Aajan so much. – Hoang Mar 01 '16 at 03:33