PHP:数组到 HTML 树结构

问题描述 投票:0回答:4

我有一个任务,我必须从给定的数组中获取层次结构树。数组中的数组看起来:

$commentsArray = [
    [1, 1, 'Comment 1'],
    [2, 1, 'Comment 2'],
    [3, 2, 'Comment 3'],
    [4, 1, 'Comment 4'],
    [5, 2, 'Comment 5'],
    [6, 3, 'Comment 6'],
    [7, 7, 'Comment 7'],
];

现在我需要将输出输出到 html 中,例如:

Comment 1
-- Comment 2
----Comment 3 
------Comment 6
----Comment 5
--Comment 4
Comment 7  

我的代码不起作用:

<?php

$commentsArray = array(
    array(
        'id' => 1,
        'parent_id' => 1,
        'content' => 'Comment 1'
    ),
    array(
        'id' => 2,
        'parent_id' => 1,
        'content' => 'Comment 2'
    ),
    array(
        'id' => 3,
        'parent_id' => 2,
        'content' => 'Comment 3'
    ),
   ...
);

$new = array();

foreach ($commentsArray as $comment){
    $new[$comment['parent_id']][] = $comment;
}

$tree = createTree($new, array($commentsArray[0]));

echo '<pre>';
print_r($tree);
echo '</pre>';

function createTree(&$list, $parent){
    
    $tree = array();
    
    foreach ($parent as $k=>$l){
        
        if(isset($list[$l['id']])){
            $l['children'] = createTree($list, $list[$l['id']]);
        }
        
        $tree[] = $l;
    } 
    
    return $tree;
}

我尝试在没有 $commentsArray 的第一个元素的情况下运行脚本并且它有效但我需要第一个元素

php arrays tree treeview
4个回答
0
投票

我试着这样做,但是我丢失了数组的最后一个元素;D

function generateHTML($commentsArray, $parentId = 1, &$processedIds = []) {
    
    $tree = '<ul>';
    
    foreach ($commentsArray as $item) {
        
        if ($item[1] === $parentId && !in_array($item[0], $processedIds)) {
            
            $processedIds[] = $item[0];
            
            $tree .= '<li>' . $item[2];
            $tree .= generateHTML($commentsArray, $item[0], $processedIds);
            $tree .= '</li>';
            
        }
        
    }
    
    return $tree . '</ul>';
}

echo generateHTML($commentsArray);

result_photo


0
投票
<?php

$comments = [
    [1, 1, 'Comment 1'],
    [2, 1, 'Comment 2'],
    [3, 2, 'Comment 3'],
    [4, 1, 'Comment 4'],
    [5, 2, 'Comment 5'],
    [6, 3, 'Comment 6'],
    [7, 7, 'Comment 7'],
];

$map = [];

foreach($comments as $c) {
    $id = $c[0] === $c[1] ? 0 : $c[1];
    $map[$id][] = $c;
}

function print_comments($arr, $depth) {
    global $map;
    foreach($arr as $c) {
        echo str_repeat("--", $depth) . "{$c[2]}\n";
        print_comments($map[$c[0]] ?? [], $depth+1);
    }
}

print_comments($map[0], 0);

0
投票

我自己做的。但无论如何谢谢!

<?php

class CommentService
{
/**
 * @param array $commentsArray
 *
 * @return string
 */
public function getHierarchyTreeDOM(array $commentsArray): string
{
    $processedIds = [];

    $htmlDOM = '<ul>';

    foreach ($commentsArray as $comment) {

        if ($comment[0] === $comment[1]) {
            $htmlDOM .= '<li>' . $comment[2];
            $htmlDOM .= $this->buildHierarchyRecursively($commentsArray, $comment[0], $processedIds);
            $htmlDOM .= '</li>';
        }

    }

    return $htmlDOM . '</ul>';
}

/**
 * @param array $commentsArray
 * @param int $parentId
 * @param array $processedIds
 *
 * @return string
 */
private function buildHierarchyRecursively(array $commentsArray, int $parentId = 1, array &$processedIds = []): string
{
    $htmlDOM = '<ul>';

    foreach ($commentsArray as $item) {

        if ($item[0] !== $parentId && $item[1] === $parentId && !in_array($item[0], $processedIds)) {
            $processedIds[] = $item[0];

            $htmlDOM .= '<li>' . $item[2];
            $htmlDOM .= $this->buildHierarchyRecursively($commentsArray, $item[0], $processedIds);
            $htmlDOM .= '</li>';
        }

    }

    return $htmlDOM . '</ul>';
}

}

然后在html页面中:

<?php

require_once('CommentService.php');

$commentService = new CommentService();

$commentsArray = [
    [1, 1, 'Comment 1'],
    [2, 1, 'Comment 2'],
    [3, 2, 'Comment 3'],
    [4, 1, 'Comment 4'],
    [5, 2, 'Comment 5'],
    [6, 3, 'Comment 6'],
    [7, 7, 'Comment 7'],
];

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, 
maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Comments</title>
</head>
<body>
    <h2>Comments:</h2>
    <?php

        echo $commentService->getHierarchyTreeDOM($commentsArray);

    ?>
</body>
</html>

0
投票

您可以使用两个功能:

  • 一个迭代地创建层次结构。
  • 一个为该层次结构递归创建 HTML。
function createForest(&$list) {
    $bykey = [0 => ["children" => []]];
    foreach ($list as [$id, $parentid, $comment]) {
        $bykey[$id] = ["comment" => $comment, "children" => []];
        $bykey[$parentid == $id ? 0 : $parentid]["children"][] = &$bykey[$id];
    }
    return $bykey[0]["children"];
}

function createHtml(&$forest) {
    $html = "";
    foreach ($forest as ["comment" => $comment, "children" => $children]) {
        $html .= "<li>$comment" . createHtml($children) . "</li>";
    }
    return $html ? "<ul>$html</ul>" : "";
}

$commentsArray = [
    [1, 1, 'Comment 1'],
    [2, 1, 'Comment 2'],
    [3, 2, 'Comment 3'],
    [4, 1, 'Comment 4'],
    [5, 2, 'Comment 5'],
    [6, 3, 'Comment 6'],
    [7, 7, 'Comment 7'],
];
$forest = createForest($commentsArray);
$html = createHtml($forest);
echo $html;

输出:

© www.soinside.com 2019 - 2024. All rights reserved.