Reputation: 2917
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);
Upvotes: 0
Views: 279
Reputation: 78994
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:
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']
);
}
Upvotes: 1
Reputation: 12365
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" } } } }"
Upvotes: 0