如何设置数组的属性,以便通过json_encode得到所需的结果

时间:2015-10-06 12:45:15

标签: javascript php

预期输出

['#ff0000','#4caf50','#4caf50','#4caf50','#00bcd4','#00bcd4','#4caf50','#4caf50']

我正在获得输出

["'#ff0000','#4caf50','#4caf50','#4caf50','#00bcd4'","'#00bcd4','#4caf50','#4caf'"]

这是我的代码

$color_str=Array
(
    [0] => '#ff0000'
    [1] => '#4caf50'
    [2] => '#4caf50'
    [3] => '#4caf50'
    [4] => '#00bcd4'
)
$color_string=json_encode($color_str);

1 个答案:

答案 0 :(得分:0)

['#ff0000','#4caf50','#4caf50','#4caf50','#00bcd4','#00bcd4','#4caf50','#4caf50']

是无效的JSON,因为JSON使用"而不是'。

像这样定义数组

$color_str=Array('#ff0000','#4caf50','#4caf50','#4caf50','#00bcd4');

,生成的JSON将是

["#ff0000","#4caf50","#4caf50","#4caf50","#00bcd4"]