Sérgio Santos
Sérgio Santos

Reputation: 17

Remove keys and double quotes from a JSON-encoded string

I'm trying to change an array format from this

{"updated":"2016-01-28 02:00:02","rate":"0.1898"}

to this

[2016-01-28 02:00 , 0.1898]

I'm getting the first array format from a MySQL query and need to convert to the second format to use in a line chart.

$newVal = array();
foreach ($dbresult as $key => $value) {
    $newVal[] = json_encode(array_values($value)); 
}

echo implode(",", $newVal);

With this new code block i get this format

["2016-01-28 02:00" , "0.1898"]

But still need to get rid of the double quotes, any ideas?

Upvotes: 0

Views: 990

Answers (3)

toannh
toannh

Reputation: 112

Try this code

$string =  ' {"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
$array = json_decode($string, true);
$str = json_encode(array_values($array));
echo str_replace('"', '', $str);

Upvotes: 1

deceze
deceze

Reputation: 522636

$json = '[{"updated":"2016-01-28 02:00:02","rate":"0.1898"}]';

echo json_encode(array_map(function ($data) {
    return [$data->updated, $data->rate];
}, json_decode($json)));

In other words:

  1. JSON-decode it
  2. loop through it
  3. create a new array with updated in the first index and rate in the second
  4. JSON-encode it again

Step 3 is necessary since JSON objects don't guarantee any particular order, so relying on the decoded order of the keys is not reliable; and it also guarantees you get the data you want even if you add more keys to your objects.

Upvotes: 1

Sharma Vikram
Sharma Vikram

Reputation: 2480

you should try this

    $str ='{"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
    $data=json_decode($str);
    echo '<pre>';
    echo 'json decode it returns ojbects<br>';
    print_r($data);
    echo 'convert object into array<br>';
    $data=(array)$data;
    print_r($data);
    echo 'Your Output<br>';
    echo json_encode(array_values($data));

O/P :-

Upvotes: 0

Related Questions