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

$students=[
    'Kima'=>[
        'SUBJECT'=>[
            'English'=>52,
            'Maths'=>33,
            'Science'=>44
        ],
        'CERTIFICATES'=>[ 'TFC'=>true,'TTM'=>false ]
        ],
    'Zaua'=>[
        'SUBJECT'=>[
            'English'=>60,
            'Maths'=>50,
            'Science'=>60
        ],
        'CERTIFICATES'=>['TFC'=>false,'TTM'=>true]
        ],
    'Lawma'=>[
        'SUBJECT'=>[
            'English'=>41,
            'Maths'=>79,
            'Science'=>40
        ],
        'CERTIFICATES'=>['TFC'=>false,'TTM'=>false]
    ],
    'Pari'=>[
        'SUBJECT'=>[
            'English'=>55,
            'Maths'=>43,
            'Science'=>53
        ],
        'CERTIFICATES'=>['TFC'=>false,'TTM'=>true]
    ]
];







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;
}

print_r($students);



 

No comments :

Post a Comment