【发布时间】:2016-04-21 10:14:56
【问题描述】:
当尝试将 php 数组变量 json_encode 为 javascript 变量时会出现问题:
var duration_options = <?=json_encode($duration_options)?>;
var duration_options_items = '';
$.each(duration_options,function(index, value) {
if(init_act_duration == value){
var selected_option = 'selected=selected';
}else{
var selected_option = '';
}
duration_options_items = duration_options_items + '<option value="'+index+'" '+selected_option+'>'+value+'</option>';
});
duration_options_items = '<select class="form-control select2 select_ajax select_ajax_duration" name="edit_activity_duration" style="width:100%">'+duration_options_items+'</select>';
PHP 数组是
Array
(
[0.5] => 0.5
[1] => 1
[1.5] => 1.5
[2] => 2
[2.5] => 2.5
[3] => 3
[3.5] => 3.5
[4] => 4
)
当我在我的 javascript 中使用该 json 时,在 json_encode 之后,数组就像:
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[0.5] => 0.5
[1.5] => 1.5
[2.5] => 2.5
[3.5] => 3.5
)
只是不明白为什么,也不知道如何正确订购它们
【问题讨论】:
-
json_encode变成:...真的是Javascript数组吗?
-
检查这个:- eval.in/557376 。它清楚地表明您在
json_encode之前对您的数组进行了处理 -
请编辑问题并发布您的代码。不要只是假设 PHP 坏了 ;-)
-
@Anant 不一定,只需将编码的 json 粘贴到浏览器控制台(在我的情况下为 chrome),您就会看到 reordered 版本。问题是,问题可能缺少 "when I use that json in my javascript..." 部分。
-
就用
json_encode(array_values($duration_options));吧,反正十进制键没有多大意义(键等于值)。
标签: javascript php arrays json encode