如何将从循环获得的值赋给数组

时间:2016-05-04 13:55:12

标签: php arrays codeigniter

我想将从foreach循环获得的值分配或存储到数组中,以便我可以对值使用数组排序函数。请在下面是我的代码。它似乎为每个循环创建一个全新的数组,其中key = 0.如果我将print语句放在循环下面,它将只显示从循环中获得的最后一个值。我不明白它是如何解释的 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>";

    }
?>

输出 ARRAY

5 个答案:

答案 0 :(得分:4)

您需要添加[]以生成正确的数组。试试这个:

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

答案 1 :(得分:3)

在循环外创建一个空数组:

$Array = array();

在循环中添加值:

$Array[] = $mark_obtained;

循环结束后测试你的数组:

print_r($Array);

答案 2 :(得分:1)

要仅创建一个数组,请使用以下格式:

// access modifiers omitted for brevity
class MyApplication extends Application {

    String name;

    String getName() {
        return name;
    }

    void setName(String name) {
        this.name = name;
    }
}

答案 3 :(得分:1)

尝试使用array_push()。 例如:

<?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现在是一个平面阵列......

问候。

答案 4 :(得分:1)

我认为这就是你想要的......

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