【问题标题】:Recursive Multidimensional Array to HTML nested code递归多维数组到 HTML 嵌套代码
【发布时间】:2017-03-12 02:24:43
【问题描述】:

我正在尝试使用递归函数从 PHP 中的多维数组创建嵌套的 HTML 代码块。但是我似乎无法以嵌套顺序打印标签。

这是原始数组:

$array_1 = 
		  array
		  (
			  array
				  (
					  'id' => '1',
					  'tag' => 'div1',
					  'parent' => '0'
				  ),
					  
			  array
				  (
					  'id' => '2',
					  'tag' => 'div2',
					  'parent' => '1'
				  ),
			  array
				  (
					  'id' => '3',
					  'tag' => 'div3',
					  'parent' => '2'
				  ),
			  array
				  (
					  'id' => '4',
					  'tag' => 'div4',
					  'parent' => '2'
				  ),
			  array
				  (
					  'id' => '5',
					  'tag' => 'div5',
					  'parent' => '0'
				  ),
			  array
				  (
					  'id' => '6',
					  'tag' => 'div6',
					  'parent' => '5'
				  ),
			  array
				  (
					  'id' => '7',
					  'tag' => 'div7',
					  'parent' => '0'
				  )
		  );

我做的第一件事是使用一个函数将这个数组变成一个多维数组,通过使用每条记录的父元素作为参考构建一个树形结构:

function buildTree(array $elements, $parentId = 0) {
    
	$branch = array();

    foreach ($elements as $element) 
	{
        if ($element['parent'] == $parentId) 
		{
            $children = buildTree($elements, $element['id']);
            
			if ($children) 
			{
                $element['children'] = $children;
            }
			
			$branch[] = $element;
        }
    }

    return $branch;
}

$tree_1 = buildTree($array_1);

完成后,多维数组应如下所示:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => div1
            [parent] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [name] => div2
                            [parent] => 1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 3
                                            [name] => div3
                                            [parent] => 2
                                        )

                                    [1] => Array
                                        (
                                            [id] => 4
                                            [name] => div4
                                            [parent] => 2
                                        )

                                )

                        )

                )

        )

    [1] => Array
        (
            [id] => 5
            [name] => div5
            [parent] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 6
                            [name] => div6
                            [parent] => 5
                        )

                )

        )

    [2] => Array
        (
            [id] => 7
            [name] => div7
            [parent] => 0
        )

)

接下来要做的是以嵌套顺序输出 html 元素。在此示例中,我使用符号标签名称,例如 div1、div2 等;但实际上它们可以是任何 html 标签,如 div、h1、ul、li、form 等;以及它们的开始和结束标签。

为此,我使用以下递归函数,但我的问题是它没有按应有的嵌套顺序显示 html 元素。

function recursive($array, $level = 0)
{
    foreach($array as $key => $value)
	{
        
		if (!is_array($value) && $key == "tag") { echo str_repeat(" ", $level), "[".$value."]", ''; }
		
		//If $value is an array.
        if(is_array($value))
		{
			//We need to loop through it.
            recursive($value, $level + 1);
        } 
		else
		{
            //It is not an array, so print it out.			
			if ($key == "tag") { echo "[/".$value."]", '<br>'; }
						
        }
    }
}

$tree_2 = recursive($tree_1);

echo $tree_2;

这是它当前从数组中输出 html 标记的方式:

[div1][/div1]

   [div2][/div2]

     [div3][/div3]

     [div4][/div4]

 [div5][/div5]

   [div6][/div6]

 [div7][/div7]

这就是基于多维数组的嵌套顺序实际输出html标签的方式(请注意一些div标签如何在它们的结束元素之前包含其他div标签):

[div1]
   [div2]
     [div3][/div3]
     [div4][/div4]
   [/div2]
[/div1]
 
[div5]
   [div6][/div6]
[/div5]
 
[div7][/div7]

我怎样才能像上一个示例一样以正确的嵌套顺序打印 html 标签?我错过了什么?非常感谢!

【问题讨论】:

    标签: php arrays recursion multidimensional-array tree


    【解决方案1】:

    问题在于,$tree_1 数组中的键 tagchildren 之前。

    虽然我会亲自更改您的数据结构以使其“更容易”在递归函数中使用,但您可以更改您的 recursive 函数以使其像这样工作:

    function recursive($array, $level = 0)
    {
        // Check if we are using an associative array or indexed array
        if(isset($array['tag'])) {
            echo str_repeat("&nbsp;", $level), "[" . $array['tag'] . "]", '';
    
            if(isset($array['children'])) {
                echo "<br />";
                recursive($array['children'], $level + 1);
                echo str_repeat("&nbsp;", $level), "[/" . $array['tag'] . "]" , '';     
            } else {
                echo "[/" . $array['tag'] . "]";
            }
    
            echo "<br />";
        } else {
            foreach($array as $key => $value)
            {
                recursive($value, $level + 1);
            }
        }
    }
    

    在需要的地方添加额外的换行符和格式

    【讨论】:

      【解决方案2】:

      重写你的函数:

      function recursive2($array, &$level, $indentClosingTag = true)
      {
        $level++;
        for($i = 0; $i<count($array); $i++) {
          $data = $array[$i];
          $indent = str_repeat('&nbsp;', $level);
      
          echo $indent . "[".$data['tag'].']';
          if (isset($data['children'])) {
            echo '<br>';
            $level++;
            recursive2($data['children'], $level, true);
            $level--;
          } else {
            $indentClosingTag = false;
          }
          echo ($indentClosingTag ? $indent : ''). "[/".$data['tag'].']'.'<br>';
        }
        $level--;    
      }
      
      $l = 0;
      recursive2($tree_1, $l);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 2020-03-21
        • 2017-02-02
        • 1970-01-01
        • 1970-01-01
        • 2013-11-11
        • 2017-12-28
        相关资源
        最近更新 更多