I want to assign or store the values I get from foreach loop into an array, so that I can use array sort function for the values. Please below is my code. It seems to create a whole new array for every loop with key = 0. And if i place the print statement below the loop, it will display only the last value obtained from the loop. I don't understand how it was explained in This Question
<?php
$studen_id = $this->db->get_where('student' , array('class_id' => $class_id))->result_array();
foreach($studen_id as $row){
$mark_obtained = $this->crud_model->get_exam_total($row2['exam_id'] , $class_id , $row['student_id']);
$student_mark = array($mark_obtained);
// rsort($student_mark);
echo "<li>"; print_r($student_mark); echo "</li>";
}
?>
You need to add [] to generate proper array. Try this:
<?php
$studen_id = $this->db->get_where('student' , array('class_id' => $class_id))->result_array();
$student_mark = array();
foreach($studen_id as $row){
$mark_obtained = $this->crud_model->get_exam_total($row2['exam_id'] , $class_id , $row['student_id']);
$student_mark[] = $mark_obtained;
}
?>
Create an empty array outside the loop:
$Array = array();
Within the loop add the values:
$Array[] = $mark_obtained;
After the end of loop test your array:
print_r($Array);
To create only one array, use this form:
$student_mark = array();
foreach($studen_id as $row){
$mark_obtained = ......
$student_mark[] = $mark_obtained;
....
Try to use array_push() . example:
<?php
$student_mark = array();
$studen_id = $this->db->get_where('student' , array('class_id' => $class_id))->result_array();
foreach($studen_id as $row){
$mark_obtained = $this->crud_model->get_exam_total($row2['exam_id'] , $class_id , $row['student_id']);
array_push($student_mark, $mark_obtained);
// rsort($student_mark);
echo "<li>"; print_r($student_mark); echo "</li>";
}
?>
$student_marks
is now a flat array...
Regards.
I think this is what you want ...
$student_mark =array();
$studen_id = $this->db->get_where('student' , array('class_id' => $class_id))->result_array();
foreach($studen_id as $row)
{
$mark_obtained = $this->crud_model->get_exam_total($row2['exam_id'] , $class_id , $row['student_id']);
$student_mark[] = $mark_obtained;
}
sort($student_mark);
$arrlength = count($student_mark);
for($x = 0; $x < $arrlength; $x++)
{
echo "<li>".$student_mark[$x]."</li>";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.