gpt4 book ai didi

php - 将连接结果映射为相关行下的数组

转载 作者:行者123 更新时间:2023-11-29 10:36:18 24 4
gpt4 key购买 nike

在 Laravel 中,我使用 eloquent 从数据库中获取数据。

我有两个表“问题”和“选项”我正在使用 Eloquent 方法将“选项”连接到“问题”

$questions = Question::join('options', 'options.question_id', 'questions.id');

return QuestionResource($questions);

这确实会返回预期的数据集合,其中相同的问题在集合中出现多次,并且每个问题都与不同的选项连接,其中“options.question_id”和“question.id”相同。

[
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "city",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "planet",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "continent",
answer: true
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 2,
value: "comedian",
answer: false
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 1,
value: "genius scientist",
answer: true
}
]

我希望所有选项都嵌套在相关问题中的一个键下。喜欢

[
{
id: 1,
text: "Africa is a...?",
// joined options
options: [
{value: "city", answer: false},
{value: "planet", answer: false},
{value: "continent", answer: true}
]
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined options
options: [
{value: "comedian", answer: false},
{value: "genius scientist", answer: true}
]
}
]

我可以用 Laravel 的 eloquent 来实现这一点吗?否则我必须应用额外的逻辑。

最佳答案

如果您想应用额外的逻辑,此代码可能会帮助您

    <?php 
$combinedqst = array('id' => '','text'=> '','option'=> array('value' => array('value' => ,'' ), 'answer' => ''));
$ids = array('id' => , '');
//loop through questions array 1st loop for getting the question
foreach($questions as $question) {
$count = 0;
//check if question is already looped
if(!in_array($question["id"],$ids)){
//2end loop to get the opstions
foreach($questions as $question_check) {

if($question_check["id"] == $question["id"]){
if($count == 0){
$combinedqst["id"] = $question["id"];
$combinedqst["text"] = $question["text"];
}
$count = 1;
array_push($combinedqst["option"]['value'],$question_check['value']);
array_push($combinedqst["option"]['answer'],$question_check['answer']);
}

}
}
array_push($ids,$question["id"]);
}
vardump($combinedqst);

关于php - 将连接结果映射为相关行下的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46376782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com