我正试图操纵一个Eloquent对象。下面是Json中对象的结构,以便于阅读。每条记录都是一个问题的答案。您会注意到记录中有两个实例(1和2)。
以下是目标:
1)将所有相关的“答案”字段放入一个记录中(按“实例”分组 - 定义关系 - 如下所述)
2)按实例对记录进行分组。我需要所有带有“instance”的记录:“1”组合在一起,所有记录都带有“instance”:“2”组合在一起。
3)维护集合中的项目以传递给视图
期望的格式:(注意记录如何按“实例”分组,我现在可以遍历它们,这是我的目标)
[
{
"1": "John",
"2": "A",
"3": "Livingston",
"instance": "1"
},
{
"1": "Jake",
"2": "B",
"3": "Miller"
"instance": "2"
}
]
RAW OUTPUT:
[
[
{
"id": 1241,
"project_id": 1080,
"user_id": 1,
"question_id": 46,
"answer": "John",
"instance": "1"
},
{
"id": 1271,
"project_id": 1080,
"user_id": 1,
"question_id": 46,
"answer": "Jake",
"instance": "2"
}
],
[
{
"id": 1242,
"project_id": 1080,
"user_id": 1,
"question_id": 47,
"answer": "A",
"instance": "1"
},
{
"id": 1272,
"project_id": 1080,
"user_id": 1,
"question_id": 47,
"answer": "B",
"instance": "2"
}
],
[
{
"id": 1240,
"project_id": 1080,
"user_id": 1,
"question_id": 48,
"answer": "Livingston",
"instance": "1"
},
{
"id": 1279,
"project_id": 1080,
"user_id": 1,
"question_id": 48,
"answer": "Miller",
"instance": "2"
}
],
]
这里有一些代码让我接近理想的结果,但如果每个实例中的答案数量不完全匹配,则抛出偏移量错误:
// the $answers object is the one I'm trying to manipulate.
// for context, $answers->toJson() gives the raw json output above
foreach($answers as $answer)
{
$numOfAnswers = $answer->count();
}
$i = 0;
while ($i < $numOfAnswers) {
$resource{$i} = $answers->fetch($i);
$i++;
}
// This returns 'John' on the first loop, 'Jake' on the second loop, etc.
foreach($resource as $answerGroup)
{
$answerGroup->fetch('answer')[1]
}
答案 0 :(得分:1)
将键和数字索引组合在一个数组中并不是一个好的风格......无论如何我操纵多维数组,这就是我得到的:
$answers = [];
foreach ($initialCollection as $item) {
foreach ($item as $answer) {
$instance = $answer['instance'];
if (!isset($answers[$instance])) {
$answers[$instance] = [
'instance' => $instance,
'answers' => [$answer['answer']],
];
} else {
$answers[$instance]['answers'][] = $answer['answer'];
}
}
}
试试这个并检查结果。您可能希望从中创建新的集合。