我正在寻找在我的字符串数组上添加大括号{}的方法:
print_r(json_encode($temp));
temp = [{"Red":1,"Blue":2,"Green":2}]
我通过以下方式创建值:
$query_final = (my query);
$query = $this->db->query($query_final)->result_array();
$res = array_count_values(array_column($query, 'status'));
array_push($temp, $res);
print_r(json_encode($temp));
成为:
print_r(json_encode($temp));
temp = [{"Red": "1"},{"Idle":"2"},{"Overload":"2"}]
到目前为止,我已经尝试使用implode:
$temp = implode(",", $temp);
print_r(json_encode($temp));
但是它只是给出了错误,有什么办法做正确的事吗?
答案 0 :(得分:0)
使用json_decode($temp, true);
答案 1 :(得分:0)
您可以在数组上使用json_encode来获取JSON。像这样:
$temp = ['Red' => 1,
'Blue' => 2,
'Green' => 2
];
print_r(json_encode($temp)); // {"Red":1,"Blue":2,"Green":2}
答案 2 :(得分:0)
array_count_values()
返回值的列表及其出现的次数,因此仅使用array_push()
会将整个数组添加为1,并为您提供获得结果的结果。
相反,您可以一次将结果添加到$temp
数组中,并在之后获得结果...
$temp = [];
$res = array_count_values(array_column($query, 'status'));
foreach ( $res as $key=>$item ) {
$temp[] = [$key => $item];
}
print_r(json_encode($temp));