【发布时间】:2015-04-16 23:00:36
【问题描述】:
我正在使用递归函数来创建 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;
【问题讨论】:
-
在此处发布您的代码,而不是图片。
-
并发布代码,而不仅仅是数据结构
-
您好,您需要向我们展示一些您尝试过的代码,并具体说明您遇到的问题。目前,这似乎是要求其他人为您编写代码,这不是本网站的目的。
-
我也发布了代码。
-
写一个 mcve:stackoverflow.com/help/mcve
标签: php arrays multidimensional-array foreach