Php 如何将从循环中获得的值分配给数组
我想将从foreach循环获得的值分配或存储到一个数组中,这样我就可以使用数组排序函数对这些值进行排序。下面是我的密码。它似乎为key=0的每个循环创建了一个全新的数组。如果我将print语句放在循环下面,它将只显示从循环中获得的最后一个值。我不明白这是怎么解释的Php 如何将从循环中获得的值分配给数组,php,arrays,codeigniter,Php,Arrays,Codeigniter,我想将从foreach循环获得的值分配或存储到一个数组中,这样我就可以使用数组排序函数对这些值进行排序。下面是我的密码。它似乎为key=0的每个循环创建了一个全新的数组。如果我将print语句放在循环下面,它将只显示从循环中获得的最后一个值。我不明白这是怎么解释的 输出 您需要添加[]以生成正确的数组。试试这个: <?php $studen_id = $this->db->get_where('student' , array('class_id' => $
输出
您需要添加[]以生成正确的数组。试试这个:
<?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;
}
?>
在循环外部创建一个空数组:
$Array = array();
在循环中添加值:
$Array[] = $mark_obtained;
循环结束后,测试阵列:
print_r($Array);
要仅创建一个数组,请使用以下表单:
$student_mark = array();
foreach($studen_id as $row){
$mark_obtained = ......
$student_mark[] = $mark_obtained;
....
尝试使用。
例如:
<?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
现在是一个平面数组
问候。我想这就是你想要的
$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>";
}
$student\u mark=array();
$studen_id=$this->db->get_where('student',array('class_id'=>$class_id))->result_array();
foreach($studen\u id作为$row)
{
$mark_acquired=$this->crud_model->get_exam_total($row2['exam_id'],$class_id,$row['student_id']);
$student_mark[]=获得$mark_;
}
排序(学生分数);
$arrlength=计数(学生分数);
对于($x=0;$x<$arrlength;$x++)
{
回音“”$student_mark[$x]。“ ”;
}
3个正确答案,但“西部最快的枪”得到了我的投票:-)另外,根据OP的问题,我建议在foreach()循环之后显示一个使用排序函数的示例。嗯,它不应该是array\u push($student\u mark,$mark\u获得)代码>?对不起,我编辑我的帖子是为了使用array\u merge。。。你说的是array()函数,是的,复制/粘贴错误;)$mark\u获得的
不是一个数组,因此array\u merge()
将产生一个错误…感谢各位提供的所有有效答案。我很感激
$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>";
}