user3792206 user3792206 - 3 months ago 8
PHP Question

Re-arranging an array recursively in PHP

Please I have an array of data arranged in this format

[
(int) 0 => [
'student_id' => 'AF/2016/SCH/001',
'AF101' => (float) 56,
'AF102' => (float) 46,
],
(int) 1 => [
'student_id' => 'AF/2016/SCH/003',
'AF101' => (float) 76,
'AF102' => (float) 39,
],


but I need a function that can read the array and rearrange it to appear in the format

[
(int) 0 => [
'student_id' => 'AF/2016/SCH/001',
'course_id' => 'AF101',
'total' => '56',
],
(int) 2 => [
'student_id' => 'AF/2016/SCH/001',
'course_id' => 'AF102',
'total' => '46',
],
(int)3 => [
'student_id' => 'AF/2016/SCH/003',
'course_id' => 'AF101',
'total' => '76'
],
(int) 4 => [
'student_id' => 'AF/2016/SCH/003',
'course_id' => 'AF102',
'total' => '39'
],

]


In the second array which is derived from the first array, the

'AF101' => '56'


is interchanged to

'course_id' => 'AF101',
'total' => '56'


Any contributions and suggestions are welcome

Answer

This code works for your problem, assuming that there is nothing else in each student sub-array than the id and courses with scores:

$original_array = [
    0 => [
        'student_id' => 'AF/2016/SCH/001',
        'AF101' => 56,
        'AF102' => 46,
    ],
    1 => [
        'student_id' => 'AF/2016/SCH/002',
        'AF101' => 76,
        'AF102' => 39,
    ],
];
$newarray = [];

foreach ($original_array as $student)
{
    $student_id = $student['student_id'];
    unset($student['student_id']);
    foreach ($student as $course_id => $score)
    {
        $newarray[count($newarray)] = $newarray[count($newarray)] = [
            'student_id' => $student_id,
            'course_id' => $course_id,
            'total' => $score,
        ];

    }
}
echo '<pre>';
var_dump($newarray);