Reputation: 2704
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
)
)
Upvotes: 1
Views: 7406
Reputation: 1479
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>
Upvotes: 2
Reputation: 64536
A simple JSON encode will do it:
echo "<script>var options = " . json_encode($array) . ';</script>';
Upvotes: 7
Reputation: 70903
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.
Upvotes: 2