Hi I have this simple php array containing category hierarchy
<?php
$categories = [
'Games',
'-Sports',
'--Footbal',
'--Basketball',
'-Action',
'--FPS',
'--RPG',
'-SIM',
];
Once echo, it will looks like this (A simple category hierarychy):
Games
-Sports
--Footbal
--Basketball
-Action
--FPS
--RPG
-SIM
Currently I want to use the Bootstrap Tree plugin by https://github.com/jonmiles/bootstrap-treeview and need to prepare my data to look like this
var tree = [
{
text: "Games",
nodes: [
{
text: "Sports",
nodes: [
{
text: "Footbal"
},
{
text: "Basketball"
}
]
},
{
text: "Action",
nodes: [
{
text: "FPS"
},
{
text: "RPG"
}
]
},
{
text: "SIM"
}
]
}
];
I understand I need to build an array first and later convert it into JSON. Question is how do I convert my existing array into compatible array for the required JSON?
My code so far
<?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 {
}
}
}
}
Thanks guys for helping!