2017-03-02 5 views
-2

Ich versuche ein Kommentarsystem zu erstellen, das verschachtelte Kommentare darstellt. Diese Funktion funktioniert für mich. Allerdings kann ich nicht herausfinden, wo und wie man die Daten "zurückgibt", da ich dieses div nicht wiedergeben möchte.Wie erstellt man eine rekursive Funktion in PHP?

Das Array, das ich verwende, ist multidimensional, wo "Kind" verschachtelte Kommentare enthält.

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

    } 
} 
+0

http://stackoverflow.com/questions/2648968/what-is-a-recursive-function-in-php versuchen hier –

Antwort

0

Sie müssen nur das $ -Ergebnis als Parameter an die Funktion übergeben, und fügen Sie es nach und nach hinzu.

UPD: Ich habe den Code der Funktion ein wenig in Bezug auf Ihre Antwort optimiert. Bitte beziehen Sie sich auf dieses Beispiel:

$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; 
} 
+0

Vielen Dank für die Antwort! Darf ich das noch mal sehen? Ich glaube, ich bin immer näher ... 'Funktion display_comments ($ commentsArr, $ level = 0, $ result = '') { \t foreach ($ commentsArr as $ info) { \t \t $ widthInPx = ($ level + 1) * 30; \t \t \t \t \t $ Ergebnis. = '

'; \t \t if (empty ($ info [ 'Childs'])!) { \t \t \t $ result = display_comments ($ info [ 'Childs'], $ level + 1, $ result). \t \t} \t \t \t \t return array ("HTML" => $ result); \t \t \t} // foreach } // function' –

+0

@TaylorBayouth kein Problem, die ursprüngliche Antwort sehen, habe ich mir die Freiheit genommen eine beispielhafte Struktur des verschachtelten Kommentar Baum zu liefern. –

+0

Vielen Dank. Das brachte mich in die richtige Richtung! –

Verwandte Themen