可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
For example I have a PHP array, such as this one
<?php $s= array('a','b','c','d','e','f') ; ?>
And I need to loop through it in JavaScript, any ideas how do I do that?
for ( i=0 ; i < <?php echo sizeof($s) ?> ; i++) { document.write('<?php echo $s [somehow need to get the 'i' value into here] ?>'); }
Any suggestions? Thanks!
回答1:
<?php $s= array('a','b','c','d','e','f') ; ?> <?php foreach($s as $a){ ?> document.write('<?=$a?>'); <?php } ?>
Not tested but thats one way.
回答2:
Before your ehco
/print
or else your php array we make sure it's in JavaScript syntax.
<?php $s=array('a','b','c','d','e','f'); $s_to_json=json_encode((array)$s); ?> <script type="text/javascript"> var fromPHP=<? echo $s_to_json ?>; for (i=0; i<fromPHP.length; i++) { yourValue=fromPHP[i]; } </script>
回答3:
Javascript and PHP cannot be combined. They are two completely different programs that communicate only vaguely. The PHP runs on the server computer and generates the HTML. The javascript runs on the client computer in the webbrowser and acts on that HTML. If you need to move information from PHP into Javscript somehow, then you have to store it in the HTML and have the Javascript access it through that HTML. If you need to do the reverse, move information from Javascript to PHP, have the Javascript call a PHP page with a query string.
One way to place the information in your array somewhere where Javascript can get to it, would be to echo it into a hidden div. Either in a series of ided spans or just a comma separated list. Then you can pull it out of the DOM.
For example:
<div style="display: none;" id="myArray"> <?php echo '<span id="myArray.count">'.sizeof($s).'</span>'; for ($i = 0; $i < sizeof($s); $i++) { echo '<span id="myArray.'.$i.'">'.$s[$i].'</span>'; } ?> </div>
Then in the Javascript you can access the array in the DOM:
var myArray = new Array(); for(i = 0; i < document.getElementById('myArray.count').innerHTML; i++) { document.write(document.getElementById('myArray.'+i).innerHTML); }
Disclaimer: untested code, and I don't have the time to perfect it right now. If someone else wants to comment or edit to fix any errors feel free :)
回答4:
Yes.... echo out your PHP array as a JavaScript array first, and then loop over that. Don't try looping over your PHP array; you can't.
回答5:
<?php $religion = array('1'=>'hindu','2'=>'sikh','3'=>'muslim'); ?> <script> <select name="religion_name"> <?php foreach ($religion as $key => $value) { echo" <option value=$key> $value->name </option>"; } ?> </select> </script>