1

In my PHP-script I have a multidimensional and associative array I want to "transform" into a javascript array. The array looks like this in PHP:

<?php
    $myArray = array(
        array( "value" => 1, "label" => "First" ),
        array( "value" => 2, "label" => "Second" )
    )
?>

And now I want to create that array into an equivalent array in javascript, through a foreach-loop. Something like this:

<script>
    var myArrayInJS = new Array();
        <? foreach( $myArray as $innerArray ): ?>
            // What do I write here?
        <? endforeach; ?>
</script>
Weblurk
  • 6,562
  • 18
  • 64
  • 120
  • Possible duplicate of http://stackoverflow.com/questions/4329092/multi-dimensional-associative-arrays-in-javascript – Pulkit Goyal Mar 02 '12 at 15:44

3 Answers3

7

You can just use

var myArrayInJs = <?php echo json_encode($myArray); ?>;
duri
  • 14,991
  • 3
  • 44
  • 49
  • Great! Didn't have to mess around with a foreach-loop... But I'm curious, does Javascript see no difference between json-notation and array-notation? Same thing? – Weblurk Mar 02 '12 at 15:48
  • 1
    @FoadFarkhondeh JSON is the recommended way how to create arrays and objects in Javascript. – duri Mar 02 '12 at 15:55
0

I would advise you not to put PHP inside Javascript. If you ever change your PHP variables or move your templates around it can mess things up.

Just make an Ajax request for it, return it as JSON, then you don't need to start building complex arrays. You will just have a nice tidy Object

outrunthewolf
  • 373
  • 3
  • 13
  • Technically an Array and an Object are pretty much the same thing in JS (minus a few small points). But I would definitely suggest a request... it makes life so much easier and means you can shift your js into .js files out of the templates. – outrunthewolf Mar 02 '12 at 15:57
-1

Javascript multidimensional arrays (or Objects) have the following notation:

var multi = { "key1" : "val1" , "key2" : "val2" }

And you access (and assign) them like obj.key

alert(multi.key1) // This would alert 'val1'.

Since it seems you already know the PHP side, I will let you go from here.

Hope this helps.

SenorAmor
  • 3,351
  • 16
  • 27