Reputation: 3
I'm trying to fatch some data frm database, and trying to create a new json file. However, in my output I'm getting double quotes in the array.
I tried many solutions available on Stack Overflow but no success so far. Help me remove it.
$to=array("name" => "Today","data" => $count1);
$yes=array("name" => "Yesterday","data" => $count2);
$ab=array($to,$yes);
$y=array("format" => "percent");
$z=array("labels" => $ti);
$json=json_encode(array("series" => $ab,"y_axis" => $y,"x_axis" => $z));
$fp = fopen('data.json', 'w');
fwrite($fp, $json);
fclose($fp);
Current output:
{
"series": [
{
"name":"Today","data":["123","123","123"]
}
],
"y_axis": {
"format":"percent"
},
"x_axis": {
"labels": ["00:00","00:00","00:00"]
}
}
I don't need double quotes around 123 & 00:00.
Upvotes: 0
Views: 1131
Reputation: 370
Try casting all the integer values to integer (you can cast to float with the floatval()
function):
$to=array("name" => "Today","data" => (int)$count1);
EDIT:
I have missed that the $count1
is an array. You can cast all the elements of the array to integer.
function castArrayOfStingsToArrayOfIntegers(&$array){
foreach ($array as $key => $var) {
$array[$key] = (int)$var;
}
}
castArrayOfStingsToArrayOfIntegers($count1)
You can use any other way to traverse the elements. Consider that it will have minimalistic performance impact if you have a lot of values in the array. You should think if you really need this values as integers and if this is the correct place to cast them. It can be better to cast them while you are constructing the $count1
and other similar arrays.
SECOND EDIT:
If you have a lot of items keep in mind that the cast using (int)
is a lot faster(around 2 times) than the intval(
) function.
Upvotes: 0
Reputation: 1244
You can use array_map to convert your $count1
variable to integer as follows:
$to = array("name" => "Today","data" => array_map('intval',$count1));
[Proof of concept]
<?php
$count1 = array("1","2","00:00","10");
$to = array("name" => "Today","data" => array_map('intval',$count1));
var_dump($to);
?>
Result:
array(2) {
["name"]=>
string(5) "Today"
["data"]=>
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(0)
[3]=>
int(10)
}
}
Upvotes: 0
Reputation: 2553
Try this:
For no values use floatval($var);
Ref: http://php.net/manual/en/function.floatval.php
Current output:
{"series":[{"name":"Today","data":["123","123","123"]}], "y_axis":{"format":"percent"},"x_axis":{"labels":["00:00","00:00","00:00"]}}
Handle "123","123","123"
using floatval($var);
and ["00:00","00:00","00:00"]
will come in double quotes as its strings.
Upvotes: 1