PHP JSON编码不起作用

2022-05-19 00:00:00 json arrays encode php var-dump

这是我要编码到JSON中的数组的var_ump:

array(3) { 
    [0]=> array(2) { 
        ["From"]=> string(14) "08 August 2013"
        ["To"]=> string(14) "21 August 2013"
    }
    [1]=> array(2) {
        ["From"]=> string(14) "11 August 2013"
        ["To"]=> string(14) "21 August 2013"
    }
    [2]=> array(2) { 
        ["From"]=> string(14) "12 August 2013" 
        ["To"]=> string(14) "01 August 2013" 
    } 
}

当我对其进行编码时,输出如下:

[
 {"From":"08 August 2013","To":"21 August 2013"},
 {"From":"11 August 2013","To":"21 August 2013"},
 {"From":"12 August 2013","To":"01 August 2013"}
]

但我希望是这样的:

{
 0:{"From":"08 August 2013","To":"21 August 2013"}, 
 1:{"From":"11 August 2013","To":"21 August 2013"}, 
 2:{"From":"12 August 2013","To":"01 August 2013"}
}

这是可能的,因为我以前做过,但现在使用相同的代码将不起作用


解决方案

使用JSON_FORCE_OBJECT参数;

$json = json_encode($array,JSON_FORCE_OBJECT);

这将分配数字键

相关文章