Changing json format in php
Get the solution ↓↓↓I have a json output from a database quesry that looks as follows:
[
{
"name": 1,
"value": "27.18161362"
},
{
"name": 2,
"value": "323.69645128"
},
{
"name": 3,
"value": "23.16249181"
}
]
I am trying to plug this into a script that will make charts from the data. The script requires the data to be in the following format:
{"script":
[
{"name":"1","value":27.18161362},
{"name":"2","value":323.69645128},
{"name":"3","value":23.16249181}
]
}
If it is not formatted in this way, the script claims that it is not valid json and contains no valud json head.
The output does use a valid json content header but that appears not to be enough for the script I am using.
So the question is, how can I convert the json output from a database call shown in first example, into the format the script is looking for show in the second example.
Code that creates json is fairly standard:
$stmt = $db3->prepare("SELECT week AS name, SUM(he.earnings) AS value FROM hotspot_earnings he INNER JOIN emrit_hotspots eh ON eh.hotspot_name = he.hotspot_name WHERE year = '2020' GROUP BY year, week");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json; charset=UTF-8');
echo json_encode($row, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
Answer
Solution:
$stmt = $db3->prepare("SELECT week AS name, SUM(he.earnings) AS value FROM hotspot_earnings he INNER JOIN emrit_hotspots eh ON eh.hotspot_name = he.hotspot_name WHERE year = '2020' GROUP BY year, week");
$stmt->execute();
// Change here
$row = ['script' => $stmt->fetchAll(PDO::FETCH_ASSOC)];
Answer
Solution:
Not sure if you can edit the initial json output with php. If it's called by AJAX and you can control the php file you can try something like this. Just build the new array.
$new_array = array('script' => $row);
echo json_encode($new_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function str_contains()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.