Reputation: 142
I have a string that comes in the form as "IT/Internet/Web Development/Ajax". I'm trying to create a php function that parses it and creates a JSON Object like
[{
"name": "IT",
"subcategories":[
{
"name": "Internet",
"subcategories" : [
{
"name": "Web Development",
"subcategories" : [
{
"name":"Ajax"
}]}]}]
I am having problems writing a function to do that. This is what i have so far.
$category = "IT /Internet /Web Development";
$categoryarray = split("\/", $category);
$categoryLength = count($categoryarray);
$subcategory_collection = array();
$lastCategory = array("name"=>$categoryarray[$categoryLength-1]);
array_push($subcategory_collection, $lastCategory);
for($i=$categoryLength-2; $i>=0; $i--) {
$subcategory = array("name" => $categoryarray[$i], "subcategories" => $subcategory_collection);
array_push($subcategory_collection, $subcategory);
}
This does not produce the desired output. I want the function to be able to parse any string that comes in the form of "parent/child/grandchild/great grandchild" and make it into a JSON object. if anybody could guide me in the right direction, that would be greatly appreciated
Upvotes: 1
Views: 261
Reputation: 116110
Maybe this is the right approach. I started with the deepest item and add a parent to each of them. I thought it was easier, although I don't know why. Haven't tried the other one. ;)
<?php
$input = "IT/Internet/Web Development";
$items = explode("/", $input);
$parent = new StdClass();
while (count($items))
{
$item = array_pop($items);
$object = $parent;
$object->name = $item;
$parent = new StdClass();
$parent->name = '';
$parent->subcategories = array($object);
}
echo json_encode(array($object));
Thanks for accepting! Meanwhile, I tried the other way around. I think the loop in itself is easier, but you need to remember the root object, so that adds some extra code. In the end there's not a big difference, but I think my gut feeling about reversing the order was right.
<?php
$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 ($parent)
$parent->subcategories = array($object);
else
$firstObject = $object;
$parent = $object;
}
echo json_encode(array($firstObject));
Upvotes: 1