Using Laravel 5.6, I am creating a multidimensional array that looks like this:
array:8 [
0 => array:2 [
0 => "ELA-2"
1 => 7
]
1 => array:2 [
0 => "Science-3"
1 => 9
]
2 => array:2 [
0 => "ELA-1"
1 => 5
]
3 => array:2 [
0 => "Science-2"
1 => 9
]
4 => array:2 [
0 => "ELA-4"
1 => 2
]
5 => array:2 [
0 => "ELA-3"
1 => 7
]
6 => array:2 [
0 => "Science-4"
1 => 2
]
7 => array:2 [
0 => "Science-1"
1 => 1
]
]
This was created using array_count_values and array_map (if that matters).
What I want is the data to look like this:
array:8 [
0 => array:3 [
"Subject" => "ELA"
"Level" => 2
"Count" => 7
]
1 => array:3 [
"Subject" => "Science"
"Level" => 3
"Count" => 9
]
2 => array:3 [
"Subject" => "ELA"
"Level" => 1
"Count" => 5
]
3 => array:3 [
"Subject" => "Science"
"Level" => 2
"Count" => 9
]
4 => array:3 [
"Subject" => "ELA"
"Level" => 4
"Count" => 2
]
5 => array:3 [
"Subject" => "ELA"
"Level" => 3
"Count" => 7
]
6 => array:3 [
"Subject" => "Science"
"Level" => 4
"Count" => 2
]
7 => array:3 [
"Subject" => "Science"
"Level" => 1
"Count" => 1
]
]
I am not sure how to:
- break apart the values from key[0] within each array and separate them into 2 parts—the first portion for the 'Subject' and the second portion for the 'Level'
- relabel the numeric incrementing keys (there will be 3 within each array) to the words "Subject", "Level", and "Count", respectively.
My current code looks like this:
// create an empty array
$array_holder = [];
// loop through each student
foreach($class_students as $student) {
// loop through each subject
foreach($class_subjects as $subject) {
// count each child at his/her level (rounded average)
$childs_level = AssessmentData::where('student_id', $student->id)->where('subject_id', $subject->subject_id)->avg('assessed_level');
// get the subject name
$current_subject = Subject::where('id', $subject->subject_id)->first();
// round the average
$childs_level = round($childs_level);
// convert the childs_level into a whole number
$childs_level = number_format($childs_level, 0);
// add each child by appending to an array
if ($childs_level != 0) {
$compiled_array[] = array_push($array_holder, $current_subject->short_name."-".$childs_level);
}
}
}
// count each assessed_level from the resultant array
$counted_array = array_count_values($array_holder);
// remap the array
$counted_array = array_map(null, array_keys($counted_array), $counted_array);
Additional request - sorting
I would like the results to be sorted by count so that Level 1 is first, Level 2 is second, Level 3 is third, and Level 4 is fourth. (Currently, it is sorted in the opposite order - Level 4 is first, Level 3 is second, etc.)