2016-03-15 63 views
3

我有一個名爲$comments的數組。如何按他們的類別列出評論? (操作數組)

當我var_dump($comments);

這裏是結果。

array 
    0 => 
    object(stdClass)[11] 
     public 'comment_id' => string '1' (length=1) 
     public 'comment_article_id' => string '1' (length=1) 
     public 'comment_user_id' => string '2' (length=1) 
     public 'comment' => string 'Comment to article_id 1' (length=11) 
     public 'comment_date' => string '2016-03-10 20:06:43' (length=19) 
    1 => 
    object(stdClass)[9] 
     public 'comment_id' => string '3' (length=1) 
     public 'comment_article_id' => string '1' (length=1) 
     public 'comment_user_id' => string '2' (length=1) 
     public 'comment' => string 'Another comment to article_id 1.' (length=14) 
     public 'c 
     ' => string '2016-03-10 20:06:43' (length=19) 
    2 => 
    object(stdClass)[6] 
     public 'comment_id' => string '5' (length=1) 
     public 'comment_article_id' => string '2' (length=1) 
     public 'comment_user_id' => string '2' (length=1) 
     public 'comment' => string 'Comment to article_id 2' (length=26) 
     public 'comment_date' => string '2016-03-10 20:06:43' (length=19) 

這裏是我的功能,這給了我上面的結果:

public function ListComments($userid) { 
    $comments = $this->FindComments($userid); 

    var_dump($comments); 

    } 

我想列出這樣的評論:

  • 1(這是comment_article_id)

- 對article_id的評論1

-Another註釋ARTICLE_ID 1

-Comment到ARTICLE_ID 2

我不知道該怎麼manupulate我目前的陣列來獲得這樣的結果。

我想存檔這個沒有任何改變FindComments()函數。

我必須盡我所能在這裏做ListComments()函數。

可能我需要一個foreach循環,但我沒有申請。

回答

2

通過操縱你已經收到的意見陣列要做到這一點,你只需要循環槽,並把所有的元素在二維關聯數組,其中關鍵是文章ID

$results = []; //$result = array() if using below php 5.4 

foreach ($comments as $comment) { 
    $results[$comment->comment_article_id][] = $comment; 
} 

ksort($result); //to sort from lowest highest article id 

然後輸出它就像你想要的只是需要通過$results陣列和所有的評論來打印內容。

請注意,我認爲回聲html是一種不好的做法。這只是 快速告訴你如何實現你想要的輸出。

echo '<ul>'; 
foreach ($results as $key => $comments) { 
    echo '<li>' . $key . '</li>'; 
    echo '<ul>'; 
    foreach($comments as $comment) { 
     echo '<li>' . $comment->comment . '</li>'; 
    } 
    echo '</ul>'; 
} 
echo '</ul>'; 
+0

你要解釋一些有關你的答案嗎? – HddnTHA

+0

謝謝。但是我怎樣才能達到我想要的輸出?我做了'var_dump($ result);'但我沒有得到任何線索。 – IDontKnow

2

你可以像這樣做,使得由文章編號第一鍵索引:

// create temporary associative array, keyed by comment_article_id 
$comments2 = []; 
foreach($comments as $comment) { 
    $comments2[$comment->comment_article_id][] = $comment; 
} 
// now output via that new array: 
foreach ($comments2 as $key => $arr) { 
    echo "comment article ID: $key\n"; 
    foreach ($arr as $comment) { 
     echo "comment: " . $comment->comment . "\n"; 
    } 
} 
相關問題