dongzhuo2010 2013-04-08 16:05
浏览 127
已采纳

从PDO和PHP修改生成的json

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.

  • 写回答

3条回答 默认 最新

  • dpzp5127 2013-04-08 16:13
    关注
    $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) ;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?