简体   繁体   中英

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! :)

您可能必须评估该json才能使其不仅仅是JavaScript代码中的字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM