【发布时间】:2017-09-20 14:38:26
【问题描述】:
您好,我有一个包含类别层次结构的简单 php 数组
<?php
$categories = [
'Games',
'-Sports',
'--Footbal',
'--Basketball',
'-Action',
'--FPS',
'--RPG',
'-SIM',
];
一旦回显,它将如下所示(一个简单的类别层次结构):
Games
-Sports
--Footbal
--Basketball
-Action
--FPS
--RPG
-SIM
目前我想使用 https://github.com/jonmiles/bootstrap-treeview 的 Bootstrap Tree 插件,并且需要准备我的数据看起来像这样
var tree = [
{
text: "Games",
nodes: [
{
text: "Sports",
nodes: [
{
text: "Footbal"
},
{
text: "Basketball"
}
]
},
{
text: "Action",
nodes: [
{
text: "FPS"
},
{
text: "RPG"
}
]
},
{
text: "SIM"
}
]
}
];
我知道我需要先构建一个数组,然后再将其转换为 JSON。问题是如何将现有数组转换为所需 JSON 的兼容数组?
到目前为止我的代码
<?php
$categories = [
'Games',
'-Sports',
'--Footbal',
'--Basketball',
'-Action',
'--FPS',
'--RPG',
'-SIM',
];
$tree_key = 0;
if (!empty($categories)) {
foreach ($categories as $category) {
$tree_label = $category;
$count = substr_count($tree_label, '-');
//if no dash (-) found, make it parent category
if (empty($count)) {
$tree_key = $category;
$tree_array[$tree_key] = ['text'=>$category];
}
else
{
//if one dash found, make it child of previous parent category
if ($count === 1) {
$tree_array[$tree_key]['nodes'][] = ['text'=>$category];
} else {
}
}
}
}
感谢大家的帮助!
【问题讨论】:
-
你只需要这个json对象,还是想要不管数组是什么都可以做到的代码
-
由于树是一种递归数据模型,我建议使用递归方法来解决这个问题
-
@MatthewBergwall 取决于破折号 (-) 的数量,我想让它保持嵌套,但通常数据与上面的示例非常相似,所以如果我能做到这一点就已经很好了 :)
-
@gogaz 递归方法,我能知道我应该谷歌它吗?
标签: php mysql multidimensional-array