2
您好我有这个简单的PHP数组包含类别层次如何将这个简单的数组转换为嵌套的PHP数组?
<?php
$categories = [
'Games',
'-Sports',
'--Footbal',
'--Basketball',
'-Action',
'--FPS',
'--RPG',
'-SIM',
];
一旦回声,它会看起来像这样(简单分类hierarychy):
Games
-Sports
--Footbal
--Basketball
-Action
--FPS
--RPG
-SIM
目前我想使用的引导树插件通过https://github.com/jonmiles/bootstrap-treeview和需要准备我的数据看起来像这样
var tree = [
{
text: "Games",
nodes: [
{
text: "Sports",
nodes: [
{
text: "Footbal"
},
{
text: "Basketball"
}
]
},
{
text: "Action",
nodes: [
{
text: "FPS"
},
{
text: "RPG"
}
]
},
{
text: "SIM"
}
]
}
];
我明白,我需要建立一个数组FIR st,然后将其转换为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对象,或者你想代码,可以做到这一点无论数组是什么 –
作为树是一个递归数据模型我会建议这个问题的递归方法 – gogaz
@MatthewBergwall取决于破折号( - )的数量,我想保持它的嵌套,但通常数据是非常像上面的例子,所以如果我能够实现那已经很好:) –