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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Thanks Aajab. How can I use it in javascript. Can I convert it to array in Java Script, could you help me.
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)
Thanks Aajan so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.