创建一个JSON对象

时间:2014-03-25 18:35:54

标签: php arrays json

我有一个字符串,形式为“IT / Internet / Web Development / Ajax”。我正在尝试创建一个解析它的php函数,并创建一个像

这样的JSON对象
[{
  "name": "IT",
   "subcategories":[
   {
     "name": "Internet",
      "subcategories" : [
       {
        "name": "Web Development",
        "subcategories" : [
         {
         "name":"Ajax"
          }]}]}]

我在编写函数时遇到了问题。这就是我到目前为止所做的。

$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);
}

这不会产生所需的输出。我希望函数能够解析以“父/子/孙/孙子”形式出现的任何字符串,并使其成为JSON对象。如果有人能指导我朝着正确的方向前进,那将非常感激

1 个答案:

答案 0 :(得分:1)

也许这是正确的方法。我从最深的项目开始,并为每个项目添加父项。我觉得这更容易,虽然我不知道为什么。避风港没试过另一个。 ;)

<?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));

感谢您的接受!与此同时,我尝试了另一种方式。我认为循环本身更容易,但你需要记住根对象,这样就增加了一些额外的代码。最后,没有太大的区别,但我认为我对改变订单的直觉感觉是正确的。

<?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));