Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

php - How to get Position of Comment within a Post

So I have a Post which has Comments -- I'm trying to get the Comment # position within that post. For example, a Post has 15 comments, I want to be able to get the numerical position (i.e 1 (first post), 2 (second post), 3 (third post), etc, etc), and put this into a function somehow. That way when I can call $comment->position() and it will show as the 4th, 5th, whatever position in it is in.

I've done some searching around the web and couldn't find a solution. Any help is greatly appreciated! This is what I have so far:

public function position($id,$arr)
{
    $total = $this->post->comments->count();
    $position = $this->pluck('post_id')->search($this->id) + 1;
    return ceil($total / $position);
    //$comments_per_page = 25;
    //$pos = array_search($id,$arr);
    //$pos = $pos+1;
    //return ceil($pos/$comments_per_page);
}
question from:https://stackoverflow.com/questions/65875854/how-to-get-position-of-comment-within-a-post

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should first get all your comments as collection.

// all comments as collection
$comments = $this->post->comments;

Then you can search through the collection using the search function and inserting an id you want to search for ... or any other param you want.

$id = 2;

$commentIndex = $comments->search(function($comment) use ($id) {
    return $comment->id === $id;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...