I'm having some trouble manipulating a complex array which looks like this:
Array
(
[0] => Array
(
[checklist_position] => 8
[checklist_id] => 2
[question_id] => 11
[section] => 1
[sum_a] => 332611
[sum_b] => 566201
)
[1] => Array
(
[checklist_position] => 9
[checklist_id] => 2
[question_id] => 12
[section] => 1
[sum_a] => 567725
[sum_b] => 67301
)
[2] => Array
(
[checklist_position] => 10
[checklist_id] => 2
[question_id] => 13
[section] => 1
[sum_a] => 20004
[sum_b] => 38381
)
[3] => Array
(
[checklist_position] => 11
[checklist_id] => 2
[question_id] => 14
[section] => 2
[sum_a] => 699144
[sum_b] => 139456
)
[4] => Array
(
[checklist_position] => 12
[checklist_id] => 2
[question_id] => 15
[section] => 2
[sum_a] => 791204
[sum_b] => 336133
)
[5] => Array
(
[checklist_position] => 13
[checklist_id] => 2
[question_id] => 16
[section] => 2
[sum_a] => 447501
[sum_b] => 503112
)
[6] => Array
(
[checklist_position] => 14
[checklist_id] => 2
[question_id] => 17
[section] => 2
[sum_a] => 651332
[sum_b] => 803628
)
)
What I'm trying to do is to convert it to an array like this:
Array
(
[0] => Array
(
[section] => 1
[questions] => Array
(
[0] => Array
(
[checklist_position] => 1
[checklist_id] => 1
[question_id] => 1
[section] => 1
[sum_a] => 348659
[sum_b] => 273072
)
[1] => Array
(
[checklist_position] => 2
[checklist_id] => 2
[question_id] => 2
[section] => 1
[sum_a] => 825992
[sum_b] => 189190
)
)
)
[1] => Array
(
[section] => 2
[questions] => Array
(
[0] => Array
(
[checklist_position] => 1
[checklist_id] => 1
[question_id] => 1
[section] => 1
[sum_a] => 348659
[sum_b] => 273072
)
[1] => Array
(
[checklist_position] => 2
[checklist_id] => 2
[question_id] => 2
[section] => 1
[sum_a] => 825992
[sum_b] => 189190
)
)
)
)
The problem is I don't know where to begin and any tip is very appreciated.
Thank you!
@Patroklo's solution simplified:
$result = array();
foreach($array1 as $data){
$section = $data['section'];
$result[$section]['section'] = $section;
$result[$section]['questions'][] = $data;
}
$result = array_values($result); // to re order
$array1 is your array with the current data and $result is what you expect
Probably you'll have less trouble using the section number in the keys of the arrays, like (being $array1 the first array of your question):
foreach($array1 as $data)
{
if(!array_key_exists($result[data['section']))
{
$result[$data['section']] = array('section' => $data['section']);
}
$result[$data['section']['questions'][] = $data;
}
Haven't checked it out, but it should make it.