【发布时间】:2014-05-05 18:25:39
【问题描述】:
我有以“IT/Internet/Web Development/Ajax”形式出现的字符串。我解析它并制作一个类似的 JSON 对象
[{
"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/Internet/Browsers”,我希望能够解析创建的类别并将“Browsers”作为 Internet 的子类别放置在正确的位置,然后是我的 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...
}
}
如果有人能指导我正确的方向,将不胜感激
【问题讨论】: