简体   繁体   中英

How to Create Associative array in JS

var stds = [];
<?php
  foreach ($this->students as $key => $value){
?>
    var smval = "<?php echo $value?>";
    stds.push( smval );
<?php
}
?>
alert("stds"+stds);

alert("stds"+stds);//print abc,bcd,efg so on...

The above code works fine for pushing Student Names. Now I want to push student CODES also which is there in value $key. How can i create an associative array to do that

The cleanest and safest way to do this is to convert the PHP object into a JavaScript object literal with json_encode :

var students = <?= json_encode($this->students) ?>;

// sample usage
alert (students["Tony"]);   // Tony's student code
alert (students["Geezer"]); // Geezer's student code
alert (students["Vinnie"]); // etc.
var stds = [];
<?php
  foreach ($this->students as $key => $value){
?>
    stds.push( { 'name': '<?php echo $value; ?>', 'code': '<?php echo $key; ?>' } );
<?php
  }
?>
alert("stds"+stds);

To be precise: There are no associative arrays in JavaScript. You can either use the code above, which gives you an array of objects containing your data or the code below, which gives you an object similar to the one you have in PHP.

var stds = {};
<?php
  foreach ($this->students as $key => $value){
?>
    stds[ '<?php echo $key; ?>' ] = '<?php echo $value; ?>';
<?php
  }
?>
alert("stds"+stds);
var stds = <?php echo json_encode( $this->students); ?>;

不确定阵列中有哪些键

alert( stds[0][ key1 ] +'   ' + stds[0][ key2 ])

I think you're trying to do more of a

stds[<?php echo $key?>] = '<?php echo $value; ?>';

or you can try doing it within an object demonstrated here:

http://jsfiddle.net/u3Muk/

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