1

The code in my controller action:

$model = ExamsExamResults::find()->where(['student_id'=>$student_id, 'exam_short_code'=>$test])->all();
$model = ArrayHelper::map($model, 'component_name','obt_marks', 'subject_code');
json_encode($model);

gives me following output:

{

    "002": {
        "Written": 15
    },
    "004": {
        "Practical": 45
    },
    "005": {
        "Practical": 45,
        "Written": 45
    }
}

I would like to add obt_marks for each subject_code so as to get an output similar to the following

{
    "002": {
        "marks": 15
    },

    "004": {
        "marks": 45
    },
    "005": {
        "marks": 90, //45+45

    }
}

this question gives some hints but I think Yii community will be benefitted by knowing how to do in a more Yii2 fashion (but still pure php solutions are also welcome).

Community
  • 1
  • 1
Ramesh Pareek
  • 1,601
  • 3
  • 30
  • 55

1 Answers1

1

For the solution in pure PHP you can use following to quickly sum up everything

$model = ArrayHelper::map($model, 'component_name','obt_marks', 'subject_code');
$output = [];
foreach($model as $k => $v) {
       $output[$k]['marks'] = array_sum($v);
}

Output:

Array
(
    [002] => Array
        (
            [marks] => 15
        )

    [004] => Array
        (
            [marks] => 45
        )

    [005] => Array
        (
            [marks] => 90
        )

)
Chetan Sharma
  • 2,539
  • 5
  • 25
  • 41