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>
1

3 Answers 3

7

You can just use

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

2 Comments

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?
@FoadFarkhondeh JSON is the recommended way how to create arrays and objects in Javascript.
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

1 Comment

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.
-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.

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.