Convert PHP array to JavaScript array
I want to convert a multi-dimensional PHP array to JavaScript and found this script in a post here;
<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
开发者_开发技巧?>
</script>
But the JS array remains empty. Is it because I have a multi-dimensional array?
Based on the comment you gave to one of the answers, are you sure $js_array
is empty or are you just not decoding it? If you look at the generated JavaScript, do you see var javascript_array = ;
or something else? Alternatively you could add alert( javascript_array );
to check.
EDIT: Since the variable is ok, you can now access the elements with javascript_array[0].id
, javascript_array[0].question
etc.
You can also try something more manual like this:
<?php
// $phpArray= ...
?>
<script type="text/javascript">
var jsArray = {};
<?php foreach($phpArray as $key => $val){ ?>
jsArray.<?php echo $key; ?> = "<?php echo $val; ?>";
<?php } ?>
console.log(jsArray);
</script>
If $php_array
isn't empty, try to...
var javascript_array = <?php echo $js_array; ?>;
...instead of:
echo "var javascript_array = ". $js_array . ";\n";
Hope it helps! :)
You probably have to eval that json in order for it to be more than just a string in your JavaScript code.
精彩评论