-2

I'm trying to build a commenting system that renders nested comments. This function is working for me. However, I can't figure out where and how to "return" the data, as I don't want to echo this div.

The array I'm using is multidimensional where "child" contains nested comments.

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);
    }

  }
}
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58

1 Answers1

0

You just need to pass the $result as a parameter to the function, and add to it little by little.

UPD: I've tweaked the function's code a little regarding your reply. Please refer to this example:

$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;
}
  • Thanks for the response! Mind giving this another look? I think I'm getting closer... `function display_comments($commentsArr, $level = 0, $result = '') { foreach ($commentsArr as $info) { $widthInPx = ($level + 1) * 30; $result .= '
    '; if (!empty($info['childs'])) { $result .= display_comments($info['childs'], $level + 1, $result); } return array("html" => $result); } //foreach } //function`
    – Taylor Bayouth Mar 02 '17 at 04:34
  • @TaylorBayouth no problem, see the original reply, I've taken the liberty to provide an example structure of your nested comments tree. – Dmitry Kurilsky Mar 02 '17 at 08:50