简体   繁体   English

如何在JS中创建关联数组

[英]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... alert(“ stds” + stds); //打印abc,bcd,efg等等...

The above code works fine for pushing Student Names. 上面的代码可以很好地推送学生姓名。 Now I want to push student CODES also which is there in value $key. 现在我也要推送学生CODES,它的值是$ 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 : 最干净,最安全的方法是使用json_encode将PHP对象转换为JavaScript对象常量:

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. 确切地说: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. 您可以使用上面的代码(提供包含数据的对象的数组),也可以使用下面的代码(提供与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/ http://jsfiddle.net/u3Muk/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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