1

How can I create the following using a PHP foreach from an array?

var options = [
    {text: "one", value: 1},
    {text: "two", value: 2},
    {text: "three", value: 3},
    {text: "four", value: 4}
];

my PHP Array looks like the following :

Array
(
    [0] => Array
        (
            [value] => 25000
            [text] => 25,000
        )
    [1] => Array
        (
            [value] => 25000
            [text] => 25,000
        )
)
2
  • 1
    How are the javascript and the php array related? Commented Aug 11, 2013 at 15:02
  • text => text, value => value Commented Aug 11, 2013 at 15:03

3 Answers 3

7

A simple JSON encode will do it:

echo "<script>var options = " . json_encode($array) . ';</script>';
Sign up to request clarification or add additional context in comments.

Comments

2

Using json_encode() will do the trick without any foreach. Note that you have to use utf-8-encoded text in PHP, otherwise it will fail.

1 Comment

You can use json_last_error() function to check for errors if encoding fails.
2

Perhaps this is not very correct, but you can do the following:

<script>
var options = [

<?php foreach ($myArrays as $AnArray) { ?> 
    {text: "<?php echo $AnArray['text']; ?>", value: <?php echo $AnArray['value']; ?>},
<?php
}
?>

];
</script>

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.