简体   繁体   English

在字符串数组上添加花括号 PHP

[英]Adding Curly Braces on Array of String PHP

Im looking for the way to add curly braces {} on my Array of string :我正在寻找在我的字符串数组上添加花括号 {} 的方法:

print_r(json_encode($temp));

temp = [{"Red":1,"Blue":2,"Green":2}]

Im creating that values with :我用以下方法创建该值:

$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));

become:变得:

print_r(json_encode($temp));

temp = [{"Red": "1"},{"Idle":"2"},{"Overload":"2"}]

So far i've tried to use implode :到目前为止,我已经尝试使用 implode :

$temp = implode(",", $temp);
print_r(json_encode($temp));

but it just giving the error, is there any way to do the right thing ?但它只是给出了错误,有什么办法可以做正确的事情吗?

json_decode($temp, true);解码你的 json json_decode($temp, true);

You can use json_encode on an array to get a JSON.您可以在数组上使用 json_encode 来获取 JSON。 Like so:像这样:

$temp = ['Red' => 1,
'Blue' => 2,
'Green' => 2
];

print_r(json_encode($temp)); // {"Red":1,"Blue":2,"Green":2}

array_count_values() returns a list of the values and the number of times they occur, so just using array_push() will add this entire array as 1 item and give you the results your getting. array_count_values()返回值的列表以及它们出现的次数,因此只需使用array_push()将整个数组添加为 1 个项目,并为您提供获得的结果。

Instead, you can add the results one at a time to the $temp array and get the results your after...相反,您可以一次将一个结果添加到$temp数组中,然后获得结果...

$temp = [];
$res = array_count_values(array_column($query, 'status'));
foreach ( $res as $key=>$item )   {
    $temp[] = [$key => $item];
}
print_r(json_encode($temp));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM