如何在PHP中创建递归函数



我正在尝试构建一个注释系统,以嵌套评论。这个功能对我有用。但是,我无法弄清楚在哪里以及如何"返回"数据,因为我不想回荡这个div。

我正在使用的数组是多维的,其中"孩子"包含嵌套评论。

function display_comments($commentsArr, $level = 0) {
  foreach ($commentsArr as $info) {
    $widthInPx = ($level + 1) * 30;
    echo '<div style="width:' . $widthInPx . '"></div>';
    if (!empty($info['childs'])) {
        display_comments($info['childs'], $level + 1);
    }
  }
}

您只需要将$结果作为参数传递给该函数,然后一点一点地添加到它。

upd :我对您的答复进行了一些调整。请参阅此示例:

$commentsArr = [
    [
        'text' => 'commentText1',
        'childs' => [
            [
                'text' => 'commentTextC1'
            ],
            [
                'text' => 'commentTextC2'
            ],
            [
                'text' => 'commentTextC3',
                'childs' => [
                    [
                        'text' => 'commentTextC3.1'
                    ],
                    [
                        'text' => 'commentTextC3.2'
                    ],
                ]
            ],
        ]
    ],
    [
        'text' => 'commentText2'
    ]
];

function display_comments($commentsArr, $level = 0, $result = ['html' => ''])
{
    foreach ($commentsArr as $commentInfo) {
        $widthInPx = ($level + 1) * 30;
        $result['html'] .= '<div data-test="' . $widthInPx . '">'.$commentInfo['text'].'</div>';
        if (!empty($commentInfo['childs'])) {
            $result = display_comments($commentInfo['childs'], $level + 1, $result);
        }
    }
    return $result;
}

最新更新