Reputation: 796
I will be quick with more code less talk.
I have a mySQL DB and i want to generate json from it with PHP and PDO.
<?php
require("db.php");
$dsn = "mysql:host=localhost;dbname=$dbname";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
$stmt = $pdo->prepare("SELECT * FROM table");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '{"jsons":';
echo json_encode($rows);
echo "}";
?>
The above code will return
{"jsons":[{"date_time":"2012-09-06 20:55:44","name":"theOne","message":"i am god","ip":"","device":"HTC","device_type":"Phone","class":"class1","id":"1"}]}
I want to modify the php code so my json output will be
{"jsons":[{"date_time":"2012-09-06 20:55:44","name":"theOne","message":"i am god","ip":"","devs":{"device":"HTC","device_type":"Phone","class":"class1","id":"1"}}]}
The difference is that i want to nest device
,device_type
,class
and id
into devs.
I couldn't do anything or find from google such a task.
Any help will be appreciate.
Thank you.
Upvotes: 1
Views: 421
Reputation: 7784
$push_in_devs = array("device","device_type","class","id") ;
$old_set = json_decode('{"jsons":[{"date_time":"2012-09-06 20:55:44","name":"theOne","message":"i am god","ip":"","device":"HTC","device_type":"Phone","class":"class1","id":"1"}]}') ;
$old_object = $old_set->jsons[0] ;
$new_set = new STDClass() ;
$new_set->jsons = array(0 => new STDClass) ;
$new_object = $new_set->jsons[0] ;
foreach($old_object as $name => $value){
if (!in_array(strtolower($name), $push_in_devs))
$new_object->$name = $value ;
}
$new_object->devs = array() ;
$dev = array() ;
foreach($push_in_devs as $name){
$dev[$name] = $old_object->$name ;
}
$new_object->devs[] = $dev ;
echo json_encode($new_set) ;
Upvotes: 1
Reputation: 922
$results = array();
foreach ($rows as $row) {
$result = array();
foreach ($row as $key => $value) {
if ($key === 'device' || $key === 'device_type'
|| $key === 'class' || $key === 'id') {
$result['devs'][] = $value;
} else {
$result[$key] = $value;
}
}
$results[] = $result;
}
json_encode($results);
Upvotes: 0
Reputation: 4024
Run this block right after the $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
line:
foreach ($rows as $key => $row) {
foreach ($row as $column => value) {
if ($column == 'device' || $column == 'device_type' || $column == 'class' || $column == 'id') {
$row[$key]['devs'][$column] = $value;
} else {
$row[$key][$column] = $value;
}
}
}
This will nest the values underneath the 'devs' key for each row, before proceeding to encode to JSON.
Upvotes: 0