Your Location is: Home > Php
PHP - How can I parse the JSON data in fetched SQL data?
Question
I have a table and php script. I want to fetch all datas (with PDOStatement->fetchAll() expression). I can do it. But there is a JSON column among my columns in the table. When I fetch this, the JSON data fetching as text format. I want to this JSON data be an array.
For example:
I can fetch that;
Array
(
[ID] => 1
[name] => Example
[json] => [1,2,3]
)
But I want to this;
Array
(
[ID] => 1
[name] => Example
[json] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
So I need the parse the JSON data when fetch the SQL query. Thanks.
Best answer
[json] => [1,2,3]
- this is array
and this also
[json] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
If you use Mysql write that Json in Mysql
When You fetch this in php You can
$res = your query to DB
foreach($res as &$r)
{
$r = json_decode($r['json'])
}
Example
$a[]['json'] = '{"name":"John1","age":31,"city":"New York"}';
$a[]['json'] = '{"name":"John2","age":31,"city":"New York"}';
foreach($a as &$r)
{
$r = json_decode($r['json']);
}
var_dump($a);