简体   繁体   中英

Using javascript for loop, access php array variables

A small problem that I can't seem to figure out;

So I have a php array in which I want to access through javascript using a for loop to specify the index. For example,

<?php 
 $myArray = array("a", "b", "c");
?>

<script type="text/javascript">
for(var i = 0; i < elements.length; i++){
        $('<div class="pops"> Hello '+ THIS IS WHERE I WANT THE PHP VARIABLES +'</div>').appendTo(elements[i]);
</script>

I would like to access the variables in $myArray using the 'i' in the javascript for loop since there will be the same number of variables as for loop iterations.

I have tried to read up on possible solutions to solve this but have not been able to figure it out. I have tried using the following code but came up with nothing;

$('<div class="pops"> Hello '+ <?php echo $myArray[i]; ?> +'</div>').appendTo(elements[i]);

I feel like I am running into trouble here because of the following two reasons; My syntax is probably completely wrong. The 'i' variable I am using to access the index of the array is still a javascript variable.

I am new to javascript/php so please forgive me. Thanks for any sort of help!

Easy, convert to json and add to script element.

<?php $myArray = array("a", "b", "c"); ?>

<script type="text/javascript">

// I assume phpArray length equals to elements length

var phpArray = <?php echo json_encode($myArray); ?> ;
for(var i = 0; i < elements.length; i++){
    $('<div class="pops"> Hello '+ phpArray[i] +'</div>').appendTo(elements[i]);

</script>

I see two ways of doing this: One is with JSON as @venca said.

The other way is using a php loop instead.

<?
  foreach ($myArray as $elem){
    echo '<div class="pops"> Hello '.$elem.'</div>';
  }
?>

This will generate one div with class pops for each element in your php array. If you want to run some javascript code instead, you should to something like this:

<script>
<?
  int i=0;
  foreach ($myArray as $elem){
    echo '$("<div class=\"pops\"> Hello '.$elem.'</div>").appendTo(elements['.i.'])';
    i++;
  }
?>
</script>

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