Reputation: 355
I have an array called $comments
.
when I var_dump($comments);
here is the result.
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)
And here is my function which gives me the result above:
public function ListComments($userid) {
$comments = $this->FindComments($userid);
var_dump($comments);
}
I want to list comments like this:
- 1 (which is comment_article_id)
-Comment to article_id 1
-Another comment to article_id 1.
- 2
-Comment to article_id 2
I don't know how to manupulate my current array to get such result.
I want to archive this without any changes in FindComments()
function.
I must do all I've got to do here in ListComments()
function.
Probably I need a foreach loop but I didn't apply.
Upvotes: 3
Views: 96
Reputation: 4411
To achieve this by manipulating the array of comments you already received, you just need to loop trough it and put all the elements in bidimensional associative array where the key is the article 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
Then to output it like you want you just need to go trough the $results
array and all the comments to print the content.
Please note that I consider echo-ing html as a bad practice. It's just to quickly show you how to achieve the output you desired.
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>';
Upvotes: 2
Reputation: 349964
You could do it like this, making an index keyed by that article id first:
// 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";
}
}
Upvotes: 2