0

I have a two dimensional javascript array that I want to assign to a php array.

I tried the following but it did not work:

var js_array= [[]];
js_array = <?php echo $result;?>;

I have basically created a two dimensional php array and assigned to a two dimensional javascript array.

I don't seem to see any logical issue in this code. Can someone please point out as to why this approach might not work?

Thanks.

2
  • What is in $result? If it itself is the array, the code will be js_array = Array;; if it's a string, how did you build it? Commented Nov 18, 2013 at 18:04
  • @newfurniturey,$result is a two dimensional php array. So, I want to assign it to a javascript array. Commented Nov 18, 2013 at 18:08

4 Answers 4

1

You can't echo an array, only a string. Look at the json_encode function in PHP: https://www.php.net/json_encode you'll find this does what you want.

var js_thing = <?php echo json_encode($result);?>;
Sign up to request clarification or add additional context in comments.

1 Comment

json is great for this, you can do var js_array = <?php echo json_encode($a_lot_of_things); ?>; and it will work - strings, numbers, arrays, including mixed ones, and more, always properly encoded as data.
1
var js_array= []; 
js_array = <?php echo json_encode($result);?>;

Try json_encode

Comments

0

As others pointed out, json_encode is a good option. However, the object you receive in JS is not exactly an array. The answer to this question shows you pretty simple how to use it.

Comments

0

This should do it..

<script type="text/javascript"> 
<?php 
    $arr = array(
            array(1,2,3,4,7),
            array(5,3,6,8),
            array(0,12,34,54,65)
        );
    $arr_str = '[';
    foreach ($arr as $mv) {
        $arr_str .= '[';
        foreach ($mv as $sv) {
            $arr_str .= $sv.',';
        }
        $l = strlen($arr_str);
        if(substr($arr_str, -1) == ','){
            $arr_str = substr($arr_str, 0, $l-1);
        }
        $arr_str .= '],';
    }
    $l = strlen($arr_str);
    if(substr($arr_str, -1) == ','){
        $arr_str = substr($arr_str, 0, $l-1);
    }
    $arr_str .= '];';       
?>
var js_a =<?php echo $arr_str; ?>   

Its the hard way.. and probably sucks.. ;)

Comments

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.