我有字符串形式的「IT/Internet/Web開發/ Ajax」。我分析它,並作出這樣遞歸搜索函數
[{
"name": "IT",
"subcategories":[
{
"name": "Internet",
"subcategories" : [
{
"name": "Web Development",
"subcategories" : [
{
"name":"Ajax"
}]}]}]
JSON對象我這樣做
$input = "IT/Internet/Web Development";
$items = explode("/", $input);
$parent = null;
$firstObject = null;
while (count($items))
{
$object = new StdClass();
$item = array_shift($items);
$object->name = $item;
if (count($items) == 0) {
$object->subcategories=NULL; // I made this null in order to know that this is the last item of the string that comes in
}
if ($parent)
$parent->subcategories = array($object);
else
$firstObject = $object;
$parent = $object;
}
array_push($category_collection, $firstObject); //$category_collection is an array
}
當另一個字符串進來,例如「IT /互聯網/瀏覽器」創建JSON對象,我想能夠解析在正確的地方作爲互聯網的一個子類別中創建和放置「瀏覽器」的類別,所以後來我的JSON對象看起來像
[{
"name": "IT",
"subcategories":[
{
"name": "Internet",
"subcategories" : [
{
"name": "Web Development",
"subcategories" : [
{
"name":"Ajax"
}],
{
"name":"Browsers"
}}]}]
我有問題,寫一個遞歸函數這隻會循環JSON對象來將所有內容分類在正確的位置。我在做什麼截至目前是
$arrlength = count($category_collection); //count the size of the array
$input = "IT/Internet/Browsers";
$items = explode("/",$input);
$tempVariable = array_shift($items);
$flag = false;
for ($x = 0; $x < $arrlength; $x++) {
//Here I check if the first a category with that name already exists
if ($category_collection[$x]['name'] == $tempVariable) {
$flag = true;
//Now here is where im having problems doing the recursion to check if the subcategory2 already exists and then if subcategory 3 and so on...
}
}
如果有人能指導我將不勝感激
非常感謝您對前面回答。對於遲到的回覆感到抱歉,但那正是我期待的 – aafonso1991