这是我关于 SO 的第一篇文章,所以如果这是这个问题的错误区域,我深表歉意。
我有一个用 PHP 编写的页面,我正在尝试使用名为jqTree的 jquery 插件创建具有特定布局的树。我正在使用以下返回格式从 SQL Server 2008 R2 数据库中提取页面加载数据:
╔═════════════╦═══════╦═════════╗
║ Location ║ SAN ║ Switch ║
╠═════════════╬═══════╬═════════╣
║ LocationA ║ SAN1 ║ Switch1 ║
║ LocationA ║ SAN1 ║ Switch2 ║
║ LocationA ║ SAN2 ║ Switch3 ║
║ LocationB ║ SAN3 ║ Switch4 ║
║ LocationB ║ SAN3 ║ Switch5 ║
║ LocationB ║ SAN3 ║ Switch6 ║
╚═════════════╩═══════╩═════════╝
我需要树看起来像:
LocationA
|_ SAN1
| |_ Switch1
| |_ Switch2
|_ SAN2
|_ Switch3
LocationB
|_ SAN3
|_ Switch4
|_ Switch5
|_ Switch6
根据 jqTree 站点,JSON 必须采用以下格式(我假设):
var data = [
{
label: 'LocationA',
children: [
{ label: 'SAN1',
children: [
{ label: 'Switch1'},
{ label: 'Switch2'}
]
},
{ label: 'SAN2',
children: [
{ label: 'Switch3'}
]
}
},
{
label: 'LocationB',
children: [
{ label: 'SAN1',
children: [
{ label: 'Switch4'},
{ label: 'Switch5'},
{ label: 'Switch6'}
]
}
}
];
我已经尝试过接近这样的事情:
$locations = array();
foreach ($results as $res) {
if(!in_array($res['town'], $locations, true)){
$locations[$res['town']]['children'][$res['san']][] = $res['name'];
}
}
但这显然是不正确的...
我查看了嵌套数组解决方案,但有些东西对我来说并没有点击,所以我希望有人可以帮助我解决这个问题。我可以使用另一个插件,只要我可以拥有相同/相似的功能。
希望我能够很好地描述这种情况,但如果您需要更多数据,请告诉我。
提前致谢!