如果对此有答案,请提前抱歉,但我找不到我要找的确切内容。
我目前有一个报告应用程序,它将数据结果从数据库查询返回到多维数组。每个数组都是基于id字段构建的。我希望能够将数组合并到id相同的数组中。
例如,这是一个测试结果集。如您所见,id为1的用户当前有两个结果。
Array
(
[0] => Array
(
[AssessmentQuestion] => 1
[AssessmentAnswer] => 0
[id] => 1
)
[1] => Array
(
[AssessmentQuestion] => 2
[AssessmentAnswer] => 2
[id] => 1
)
)
Array
(
[0] => Array
(
[AssessmentQuestion] => 1
[AssessmentAnswer] => 1
[id] => 2
)
)
如果id是相同的,我希望结果集看起来像这样。
Array
(
[0] => Array
(
[AssessmentQuestion] => 1
[AssessmentAnswer] => 0
[AssessmentQuestion] => 2
[AssessmentAnswer] => 2
[id] => 1
)
)
非常感谢。
以下是我正在运行的查询。有一个自定义函数ArrayFunctions :: captureArrayFromResult(),这只是捕获数组结果。 第一个查询只是获取所有活动用户条目ID,然后每个id返回所有 评估问题信息。
/**** COLLECT ALL ACTIVE USER ENTRY IDS ****/
$query = "SELECT DISTINCT ue.id
FROM user_entry ue
LEFT JOIN user_demographic_answers uda ON ue.id = uda.user_entry_id
LEFT JOIN user_assessment_answers uaa ON ue.id = uaa.user_entry_id
WHERE $condition
AND DATE(ue.datetime_finished) BETWEEN '{$this->reportDateRangeStart}' AND '{$this->reportDateRangeEnd}'";
$results = db_Query($query);
$this->reportUserEntryID = ArrayFunctions::captureArrayFromResult($results, "id", "id");
foreach($this->reportUserEntryID as $userID)
{
/**** COLLECT ASSESSMENT QUESTIONS ****/
$query = SELECT DISTINCT uaa.question_id as 'AssessmentQuestion', uaa.answer_value as 'AssessmentAnswer', ue.id
FROM user_assessment_answers uaa
LEFT JOIN report_field_options rfo ON uaa.question_id = rfo.assessment_question_id
LEFT JOIN user_entry ue ON uaa.user_entry_id = ue.id
WHERE ($condition)
AND DATE(ue.datetime_finished) BETWEEN '{$this->reportDateRangeStart}' AND '{$this->reportDateRangeEnd}'
AND ue.id IN ($userID)
ORDER BY uaa.question_id";
$results = db_Query($query);
$this->reportQuestionAssessmentAnswers = ArrayFunctions::captureArrayFromResult($results);
}
答案 0 :(得分:0)
简短回答:由于数组键必须是唯一的,因此无法按照您的要求进行操作。
我建议,在合并逻辑期间,创建一个AssesmentQuestions
和AssesmentAnswers
的数组,例如:
Array
(
[0] => Array
(
[id] => 1,
[AssesmentQuestions] => Array
(
[0] => 1,
[1] => 2
),
[AssesmentAnswers] => Array
(
[0] => 0,
[1] => 2
)
)
)
答案 1 :(得分:0)
您可以使用foreach循环来实现此目的:
$main_arr = array
(
array
(
'AssessmentQuestion' => 1,
'AssessmentAnswer' => 0,
'id' => 1
),
array
(
'AssessmentQuestion' => 2,
'AssessmentAnswer' => 2,
'id'=> 1
),
array
(
'AssessmentQuestion' => 3,
'AssessmentAnswer' => 4,
'id' => 2
),
array
(
'AssessmentQuestion' => 5,
'AssessmentAnswer' => 6,
'id'=> 1
)
);
foreach ($main_arr as $arr) {
$new_arr[$arr['id']]['id'] = $arr['id'];
$new_arr[$arr['id']]['AssessmentQuestions'][] = $arr['AssessmentQuestion'];
$new_arr[$arr['id']]['AssessmentAnswers'][] = $arr['AssessmentAnswer'];
}
var_dump($new_arr);