I'm trying to pull data from MySQL using PHP/PDO and format it as a nested JSON array.
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". And for hosts after the first to not have numbers like "2" or "3" like how the first host is.
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);