Reputation: 6812
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>
Upvotes: 1
Views: 2344
Reputation: 383
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
Upvotes: 0
Reputation: 3345
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.
Upvotes: -1
Reputation: 15351
You can just use
var myArrayInJs = <?php echo json_encode($myArray); ?>;
Upvotes: 7