我正在使用递归函数来创建一个评论/回复系统,因为yt或fb正在使用。我已经完成了这项功能,但如果我不确定该阵列有多少分支,我就无法弄清楚如何制作foreach
功能。
$coments = $this->mu_model->getByWhereStmt('comments', 'article_id', $article->id);
$comments = array();
$comm = array();
foreach($coments as $coment) {
if($coment->reply_to_msg_id == 0) {
$comm = array(
'id' => $coment->id,
'sender_id' => $coment->sender_id,
'message' => $coment->message,
'article_id' => $coment->article_id,
'like' => $coment->like,
'reply_to' => $coment->reply_to_msg_id,
'added_date' => $coment->added_date,
'deleted' => $coment->deleted,
);
$reply_id = $coment->id;
if(!empty(reply_msg($reply_id, $coments))) {
$repliess = reply_msg($reply_id, $coments);
array_push($comm, $repliess);
}
array_push($comments, $comm);
}
}
function reply_msg($reply_id, $coments) {
$replies = array();
$reply = array();
foreach($coments as $r_comment) {
if($r_comment->reply_to_msg_id != 0) {
if($r_comment->reply_to_msg_id == $reply_id) {
$reply = array(
'id' => $r_comment->id,
'sender_id' => $r_comment->sender_id,
'message' => $r_comment->message,
'article_id' => $r_comment->article_id,
'like' => $r_comment->like,
'reply_to' => $r_comment->reply_to_msg_id,
'added_date' => $r_comment->added_date,
'deleted' => $r_comment->deleted,
);
if(!empty(reply_msg($r_comment->id, $coments))) {
$repli = reply_msg($r_comment->id, $coments);
array_push($reply, $repli);
}
array_push($replies, $reply);
}
}
}
return $replies;
答案 0 :(得分:1)
怎么样:
function process($array) {
foreach ($array as $key=>$value) {
// Process the content of the array
}
if (isset($array[8])) // If we have linked arrays
foreach($array[8] as $subArray)
process($subArray);
}
PS:我还会为链接数组设置一个键,例如' children'或者'子评论'。通过这种方式,您可以调用isset($array['children'])
等等,这比通过索引访问数组更容易维护。