多级数组在php中使用xml中的elemnt缩进值?

时间:2018-07-30 06:55:10

标签: php multidimensional-array parent-child

来自具有标题和缩进值的项目的以下XML

<items>
  <item>
    <title>Module 1</title>
    <indent>0</indent>
  </item>
  <item>
    <title>Module 2</title>
    <indent>1</indent>
  </item>
  <item>
    <title>Module 3</title>
    <indent>2</indent>
  </item>
  <item>
    <title>Module 4</title>
    <indent>2</indent>
  </item>
  <item>
    <title>Module 5</title>
    <indent>1</indent>
  </item>
  <item>
    <title>Module 6</title>
    <indent>0</indent>
  </item>
</items>

需要一个具有父子关系依赖的多维数组

    [
    {
    "title": "Module 1",
    "children": [
       {
        "title": "Module 2",
        "children": [
            {
              "title": "Module 3",
              "children": []
            },
            {
                "title": "Module 4",
                "children": []
            }
        ]},
        {
            "title": "Module 5",
            "children": []
        }
        ]
    },
    {
    "title": "Module 5",
    "children": []
    }
    ]

此处的XML缩进值将决定早期xml项目的数组子级/同级和项目的序列化是否应该中断。

我尝试了许多逻辑,但没有正确地进行逻辑提示会有所帮助。 预先感谢

到目前为止我一直在尝试

foreach($xml_array as $item){
            $children['title'] =  html_entity_decode($item->title);
            $children['indent'] =  html_entity_decode($item->indent);
            $indent = html_entity_decode($item->indent);
            if($indent == 0 ){
                $toc_array[$section_counter]['children'][] = $children;
                end($toc_array[$section_counter]['children']);
                $last_indent_0_key =  key($toc_array[$section_counter]['children']);
            }else if($indent == 1){
                $toc_array[$section_counter]['children'][$last_indent_0_key]['children'][] = $children;
                end($toc_array[$section_counter]['children'][$last_indent_0_key]['children']);
                $last_indent_1_key =  key($toc_array[$section_counter]['children'][$last_indent_0_key]['children']);
            }else if($indent == 2){
                $toc_array[$section_counter]['children'][$last_indent_0_key]['children'][$last_indent_1_key]['children'][] = $children;
                end($toc_array[$section_counter]['children'][$last_indent_0_key]['children'][$last_indent_1_key]['children']);
                $last_indent_2_key =  key($toc_array[$section_counter]['children'][$last_indent_0_key]['children'][$last_indent_1_key]['children']);
            }
            $last_indent = html_entity_decode($item->indent);

        }

这段代码给了我我想要的,但是缩进值最多可以为10。 想要使用for / foreach循环来最小化此代码,因为上面的代码从来都不是一个好习惯。

0 个答案:

没有答案