douquan2023 2016-03-23 15:29
浏览 32
已采纳

如何将json的主节点作为对象数组返回?

I have created this code:

$lists = $this->db->select("SELECT * FROM LOGGER");

    $results = array();
    $results['information'] = array();

    $informations = $this->db->select("SELECT * FROM INFO WHERE code = :ccode", array("ccode" => "3"));

    foreach($informations as $item)
    {
            $results['information'][] = $item;
    }

    $response = array(
        "stack" => $lists,
        "information" => $results['information']
    );

    if(!empty($response['details']))
    {
        return '{"logger": ' . json_encode(array_values($response)) . '}';
    }

I take a stack information from my database and create two arrays. The first save all the informations stack that you can see below; the second array save only the description of the stack. Later I create a result array that save in each index stack and information the result of the two query. Now the final result is this:

{
"logger": {
   "stack": { 
    "Code": "RB01", 
    "Descri": null, 
    "Created": "2016-03-09 04:36:04"
   },
    "information": [
      {
        "Id": "RB01",
        "numeric": 1
      },
      {
        "Id": "RB01",
        "numeric": 2
      },
      {
        "Id": "RB01",
        "numeric": 3
      }
    ]
  }
}

but my goal is create a structure like the following:

{
"logger": [
   {
    "stack": [
      {
        "Code": "RB01",
        "Descri": null,
        "Created": "2016-03-09 04:36:04"
      }
    ],
    "information": [
      {
        "Id": "RB01",
        "numeric": 1
      },
      {
        "Id": "RB01",
        "numeric": 2
      },
      {
        "Id": "RB01",
        "numeric": 3
      }
    ]
  }
]
}

which change I should do in my code?

  • 写回答

2条回答 默认 最新

  • doudou8783 2016-03-23 15:55
    关注

    For me, you should just change:

    return '{"logger": ' . json_encode(array_values($response)) . '}';
    

    with :

    return '{"logger": ' . json_encode(array($response)) . '}';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 simulink单相桥式整流电路
  • ¥35 问问51单片机流水灯的代码该怎么写
  • ¥15 关于#百度#的问题:感觉已经将字体段落、字体、页边距、纸张大小、文档网络调成与论文模板一致,为什么黄色部分字体左右的间距还是不一样啊,求私信发文件接收看一下
  • ¥15 stata webuse报错
  • ¥15 TypeError: Cannot read properties of undefined (reading 'status')
  • ¥15 如何利用AI去除图片中的竹架子
  • ¥15 python 写个基金爬取的代码,自动卖出功能
  • ¥15 Linux系统启动不起来
  • ¥15 为什么运行仿真数码管不亮(语言-c语言)
  • ¥15 陈仁良《直升机飞行动力学》小扰动线化方程如何推导