我的代码如下:
<?php
$hour_list = array( '' => '', '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, '10' => 10, '11' => 11, '12' => 12, '13' => 13, '14' => 14, '15' => 15, '16' => 16, '17' => 17, '18' => 18, '19' => 19, '20' => 20, '21' => 21, '22' => 22, '23' => 23, '24' => 24 ) ;
?>
<script type="text/javascript">
function create_hour_dropdown(){
var hour_list = <?php echo json_encode($hour_list);?>;
var hr_list;
alert(JSON.stringify(hour_list));
/* Result is the following json string
{"0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","10":"10","11":"11","12":"12","13":"13","14":"14","15":"15","16":"16","17":"17","18":"18","19":"19","20":"20","21":"21","22":"22","23":"23","24":"24","":""}*/
for (var key in hour_list) {
if (hour_list.hasOwnProperty(key)) {
//alert(key + " -> " + hour_list[key]);
hr_list += '<option value="'+key+'">'+hour_list[key]+'</option>';
}
}
}
var table = document.getElementById("editview");
var rowCount = table.rows.length;
var newRow = table.insertRow(rowCount);
newRow.id = "vendor_1";
var newTD9 = document.createElement("td");
newTD9.align = "left";
newTD9.setAttribute("class", "ven_hr_min");
newTD9.innerHTML = '<select id="hmhour_ven_1" name="hmhour_ven_1" size="1" >'+hr_list+'</select>';
newTD9.setAttribute("colspan", "2");
newRow.appendChild (newTD9);
</script>
我很困惑为什么第一个数组值在jSON字符串中成为最后一个。我希望JS数组保持与PHP数组相同。请帮忙! 谢谢!
修改:我已经编辑了答案。 question被称为可能重复的答案
文档中没有任何内容明确确认数组项的顺序是保留的。但是,文档声明对于非数组属性,无法保证顺序:
但是我在这里使用json_encode按照question转换为php数组。
修改:再次编辑以显示我如何使用它。