I have a table that consists of comments. Some of them are replies to other comments and have a value set in parent_commentid table. I'm trying to create a function that checks each element in a result set if there is a value in the parent_columnid and if so take the entire element and sort it inside the element with a comment_id that matches the parent_commentid of the current element in the iteration. This is what I've come up with so far.
function sort_comments($comments){
$result = array();
foreach($comments as $comment){
if(is_null($comment['parent_commentid'])) $result[] = $comment;
else{
$parent_comment = array_search($comment['parent_commentid'], $comments);
if($parent_array !== false) $result[$parent_comment][] = $comment;
}
}
}
array_search is not the function I'm looking for but is the closets thing I could think of. Im not sure where to go from here. Keep in mind also that there can exist replies to other replies.
You need to store the comments by their own id, so that you can reference them later:
function sort_comments($comments){
$result = array();
foreach($comments as $comment){
if(is_null($comment['parent_commentid'])){
$result[$comment['commentid']] = $comment;
}else{
$parent_comment = $result[$comment['parent_commentid']]
if($parent_comment)
$parent_comment[$comment['commentid']] = $comment;
else
// what happens in this case:
// parent_commentid set, but no such comment exists?
}
}
Note the $comment['commentid']
. I don't know how you call the id of a comment (commentid
?), but since you have a column parent_commandid
you most likely do have such a column to reference your comments. Use that to store the comments, on top level or inside other comments.
To sort by internal fields of an array I usually use usort. Usort works as a recursive method so you can ensure that everytime you try to sort an element inside an array you will call your custom function. In this way you will get a more clean code.
Here is an example:
function cmp_rand_score($a, $b)
{
if($a["rand_score"] == $b["rand_score"]){
return 0;
}
return ($a["rand_score"] < $b["rand_score"]) ? 1 : -1;
}
//If you are inside a class:
usort($rows, array($this, "cmp_rand_score"));
//If not you can call directly:
usort($rows, "cmp_rand_score");
Hope it helps.