1

我会很快用更多的代码少说话。

我有一个 mySQL DB,我想用 PHP 和 PDO 从中生成 json。

<?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 "}";
?>

上面的代码将返回

{"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"}]}

我想修改 php 代码,所以我的 json 输出将是

{"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"}}]}

不同之处在于我想将 , 和 嵌套devicedevice_type开发class人员id中。

我无法做任何事情或从谷歌找到这样的任务。

任何帮助将不胜感激。

谢谢你。

4

3 回答 3

1
$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) ;
于 2013-04-08T16:13:47.427 回答
0

在该行之后运行此块$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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;
        }
    }
}

这会将值嵌套在每行的“devs”键下,然后再继续编码为 JSON。

于 2013-04-08T16:11:25.160 回答
0
$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);
于 2013-04-08T16:19:10.597 回答