Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 创建一个JSON对象_Php_Arrays_Json - Fatal编程技术网

Php 创建一个JSON对象

Php 创建一个JSON对象,php,arrays,json,Php,Arrays,Json,我有一个字符串,它的形式是“IT/Internet/Web开发/Ajax”。我试图创建一个php函数来解析它,并创建一个JSON对象,如 [{ "name": "IT", "subcategories":[ { "name": "Internet", "subcategories" : [ { "name": "Web Development", "subcategories" : [ {

我有一个字符串,它的形式是“IT/Internet/Web开发/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);
}

这不会产生所需的输出。我希望函数能够解析任何以“parent/child/孙子/曾孙”形式出现的字符串,并将其转换为JSON对象。如果有人能为我指引正确的方向,我将不胜感激

也许这是正确的方法。我从最深的项目开始,为每个项目添加一个父项。我认为这更容易,尽管我不知道为什么。我还没试过另一个


可能重复是的,我更喜欢第一种方法,只是因为它更干净,但它们都完成了任务。再次非常感谢,Golezi最终选择了第二个,因为我需要跟踪根以进行搜索。第一个也会给出根,只是它在$object变量中。容易多了
<?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));