简体   繁体   English

如何从数据库中获取数据作为嵌套的 JSON 数组?

[英]How to get data from database as nested JSON array?

I'm trying to pull data from MySQL using PHP/PDO and format it as a nested JSON array.我正在尝试使用 PHP/PDO 从 MySQL 中提取数据并将其格式化为嵌套的 JSON 数组。

Here is what I am getting:这是我得到的:

{
    "host1": [
        {
            "vmnic_name": "vmnic0",
            "switch_name": "switch1",
            "port_id": "GigabitEthernet1\/0\/1"
        },
        {
            "vmnic_name": "vmnic1",
            "switch_name": "switch1",
            "port_id": "GigabitEthernet1\/0\/2"
        }
    ],
    "host2": {
        "2": {
            "vmnic_name": "vmnic0",
            "switch_name": "switch1",
            "port_id": "GigabitEthernet1\/0\/3"
        },
        "3": {
            "vmnic_name": "vmnic1",
            "switch_name": "switch1",
            "port_id": "GigabitEthernet1\/0\/4"
        }
    }
}

I'd like for it to say "host_name": "host1", etc., rather than just "host1".我想让它说“host_name”:“host1”等,而不仅仅是“host1”。 And for hosts after the first to not have numbers like "2" or "3" like how the first host is.并且对于第一个主机之后的主机没有像第一个主机那样像“2”或“3”这样的数字。

Here is my code:这是我的代码:

$arr = array();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $key => $item) {
    $arr[$item['host_name']][$key] = array(
            'vmnic_name'=>$item['vmnic_name'],
            'switch_name'=>$item['switch_name'],
            'port_id'=>$item['port_id']
    );
}
echo json_encode($arr, JSON_PRETTY_PRINT);

If you only select those columns in the query, then it's as simple as this:如果您只在查询中选择这些列,那么就这么简单:

foreach ($result as $item) {
    $arr[$item['host_name']][] = $item;
}

If for whatever reason you must select more columns for later use, then just insert host_name and remove the $key as the index:如果出于某种原因必须选择更多列供以后使用,则只需插入host_name并删除$key作为索引:

foreach ($result as $item) {
    $arr[$item['host_name']][] = array(
            'host_name'=>$item['host_name'],
            'vmnic_name'=>$item['vmnic_name'],
            'switch_name'=>$item['switch_name'],
            'port_id'=>$item['port_id']
    );
}

This is pretty easy.这很容易。 Decode it to an array, then stick it in another one.将其解码为一个数组,然后将其粘贴到另一个数组中。

$array = json_decode($json, true);
$x = [];
$x['host_name'] = $array;

var_dump(json_encode($x, JSON_PRETTY_PRINT));

Which will give you:这会给你:

string(747) "{ "host_name": { "host1": [ { "vmnic_name": "vmnic0", "switch_name": "switch1", "port_id": "GigabitEthernet1\/0\/1" }, { "vmnic_name": "vmnic1", "switch_name": "switch1", "port_id": "GigabitEthernet1\/0\/2" } ], "host2": { "2": { "vmnic_name": "vmnic0", "switch_name": "switch1", "port_id": "GigabitEthernet1\/0\/3" }, "3": { "vmnic_name": "vmnic1", "switch_name": "switch1", "port_id": "GigabitEthernet1\/0\/4" } } } }"

https://3v4l.org/PlbON https://3v4l.org/PlbON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM