Tuesday, 16 April 2019

Add Elements to Multi-Dimensional Array in PHP

Here we have $student array which is of course a multi-dimensional array. The array contains  the names of student each of which holds the Subject and Certificate array. We are going to add a completely new element which will contain the sum of mark scored of each student. 
So this is how adding array to multi-dimensional array

        'CERTIFICATES'=>[ 'TFC'=>true,'TTM'=>false ]

We will create a empty array $marktotal and loop through the student array

$marktotal = [];
foreach($students as $k=>$v){
    //store the sum of mark scored in each subject to $marktotal
    //$k is the name of the student, we use it here as the key for the new $marktotal array,
    $marktotal[$k] = array_sum($v['SUBJECT']);

Loop the students array again to add the new element (Which is array).
foreach($students as $hming=>$course){

   //Check if the name of students exist in $marktotal key
    if(array_key_exists($hming, $
marktotal) ){
        //Create a new key 'TOTAL'
        //To get the actual mark total, we used the $hming as the $marktotal key and store it to the new key of $course
        $course['TOTAL'] = $marktotal[$hming];

    //Since we do not want to modify the first array.
    $students[$hming] = $course;