简体   繁体   中英

Remove double quotes around each element in json_encoded array

I am trying to pass an array to a GoogleChart API, which will accept an array that looks like this:

$arr=array(['Time' , 'Value'],['08' , 100 ],['10' , 200], ['12' , 300]);
$arr=(json_encode($arr));
echo($arr);
//result
[["Time","Value"],["08",100],["10",200],["12",300]]

However, when I try to create the array from my database in the following manner, I wind up with double quotes around the elements I pushed into the array, and the API will not accept the array:

WHILE($rows=mysqli_fetch_assoc($result)) {
$time[]=$rows['Time'];
$entry[]=$rows['Entry'];
    };

 $count=count($time);

$newarr=array();
for($i=0; $i<$count; $i++) {
$x="[".$time[$i].",".$entry[$i]."]";
array_push($newarr, $x);
};

array_unshift($newarr, ["Time", "Value"]);

echo(json_encode($newarr));
//result
[["Time", "Value"], "[06:08:00,250]", "[08:08:00,230]"]

Is it possible to create the array without the double quotes or to remove them?

您不想将字符串推入$newarr ,而是将数组推入:

$newarr[] = array($time[$i], $entry[$i]);

When you read from the database, the resulting value you get is ALWAYS going to be treated like a string value. If you want json_encode() to treat it like an integer, you will need to specifically cast it as an integer before doing the encoding.

You also have the additional problem that you are trying to manually build the array by concatenating brackets to it. It looks to me like you need to do something like this:

$newarr = array();
$newarr[] = array('Time', 'Value');
while($row = mysqli_fetch_assoc($result)) {
    $newarr[] = array($row['Time'], (int) $row['Entry']);
}

echo(json_encode($newarr));

I also saved some steps (and memory) by just reading the SQL results directly in $newarr . You can ignore this and do it the way you were before if you actually have some need for individual $time and $entry arrays later in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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