我是 Laravel/PHP 的新手,我正在做我的个人“玩具项目”,我遇到了一个我已经在 Google 上搜索了很长时间的问题。但是,我无法找出完美的解决方案。
问题是,我有两个集合$questions
and $answers
,我想将它们合并到一个大集合中。这是这两个集合的结构/示例
$questions
:
questions: [
{
id: 1,
title: "Why do PHP developers love Laravel? What are the things that distinguish Laravel from other PHP frameworks?",
desc: null,
user_id: 2,
created_at: "2018-07-15 06:45:57",
updated_at: "2018-07-15 06:45:57",
status: "ok"
}
]
$answers
:
answers: [
{
id: 2,
content: "Laravel is usually considered as PHP on rails! It is amazing!",
user_id: 2,
question_id: 1,
created_at: "2018-07-15 07:11:39",
updated_at: "2018-07-15 07:11:39"
},
{
id: 1,
content: "PHP is the best programming language in the world! [smile]",
user_id: 1,
question_id: 1,
created_at: "2018-07-15 07:02:21",
updated_at: "2018-07-15 07:05:12"
}
]
我努力了merge
命令,我得到了这样的东西:
$data = $questions->merge($answers);
$data = $data->sortByDesc(function($item) {
return $item->created_at;
});
data: [
{
id: 2,
content: "Laravel is usually considered as PHP on rails! It is amazing!",
user_id: 2,
question_id: 1,
created_at: "2018-07-15 07:11:39",
updated_at: "2018-07-15 07:11:39"
},
{
id: 1,
content: "PHP is the best programming language in the world! [smile]",
user_id: 1,
question_id: 1,
created_at: "2018-07-15 07:02:21",
updated_at: "2018-07-15 07:05:12"
}
]
注意到,在$data
,我找不到这个问题了,但我确实想在$data
收藏。此外,我尝试过类似的命令union
, push
, put
,他们都没有给出令人满意的解决方案。
我的代码有问题还是我根本无法在 PHP 中执行此操作?如果我的代码中有错误,我已经粘贴在这里。
public function timeline()
{
list($limit, $skip) = paginate(rq('page'), rq('limit'));
/* Retrieve questions, $questions is like I pasted above*/
$questions = question_init()
->limit($limit)
->skip($skip)
->orderBy('created_at', 'desc')
->get();
/* Retrieve answers, $answers is like I pasted above */
$answers = answer_init()
->limit($limit)
->skip($skip)
->orderBy('created_at', 'desc')
->get();
/* Merge questions and answers */
$data = $questions->merge($answers);
/* Sort by Created time */
$data = $data->sortByDesc(function($item) {
return $item->created_at;
});
$data = $data->values()->all();
return succ(['questions' => $questions, 'answers' => $answers, 'data' => $data]);
}