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条)

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档