PHP-读取带有条件的二维数组并存储结果

时间:2019-04-02 05:03:00

标签: php arrays

我要过滤$ students数组的条件:场点必须大于100。

然后,存储生成的ID,以便在$ grades数组中找到这些ID,以计算通过过滤器的$ students数组上那些ID的平均成绩。

$students = array(
    array(
        'id' => '1',
        'name' => 'Rambo Jhon',
        'tel' => '1234567',
        'email' => 'rambo@duckmail.com',
        'points' => '120',
    ),
    array(
        'id' => '2',
        'name' => 'Donald Duck',
        'tel' => '8562904',
        'email' => 'dduck@duckmail.com',
        'points' => '98',
    )
);

$grades = array(
    array(
        'student_id' => '1',
        'course_id' => 'c1',
        'grade' => '2'
    ),
    array(
        'student_id' => '2',
        'course_id' => 'c2',
        'grade' => '4'
    ),
    array(
        'student_id' => '1',
        'course_id' => 'c3',
        'grade' => '3'
    )
);

我想首先需要做的是:如果点数> 100,则将字段ID推送到另一个数组$ filtered_students。

然后,搜索存储在$ filtered_students中的id并计算其平均值。 但是我不知道怎么编码

4 个答案:

答案 0 :(得分:0)

请参阅下面的注释,其中解释了每个步骤及其作用。

$student_ids = array();

// grab all your ids for students with points more than 100 and store them in an array
foreach ($students as $student) {
    if ($student['points'] > 100) {
        $student_ids[] = $student['id'];
    }
}

// iterate over all student ids with points over 100 and call the below function
foreach ($student_ids as $student_id) {
    $averages[$student_id] = getStudentAverage($student_id,$grades);
}

print_r($averages);
// prints 2.5
// Array
// (
//    [1] => 2.5
// )


function getStudentAverage($id, $grades) {
    // filter (keep only) the grades for students with that specific id, at iteration time
    $studentGrades = array_filter($grades, function($value) use ($id){
        if ($value['student_id'] == $id){
            return true;
        }
    });

    // average works like this: 
    // get all values in the $grades array from the "grade" index (column), we previously filtered only the student we needed
    // sum them up and divide by the count
    $average = array_sum(array_column($studentGrades, 'grade')) / count($studentGrades);

    // return the average
    return $average;
}

答案 1 :(得分:0)

您可以使用数组函数将此文件存档

$filterBy = 100; // 90, etc..
$new = array_filter($students, function ($var) use ($filterBy) {
     return ($var['points'] > $filterBy);
}); // to get students detail above 100 points
$ids = array_column($new, 'id'); // to get id of the students

$studentAverage = [];
foreach($ids as $id) {
    $studentGrades = array_filter($grades, function($var) use($id) {
        return ($var['student_id'] == $id); //to fetch the students grade with id
    });
    $data['student_id'] = $id;
    $data['average']  = array_sum(array_column($studentGrades, 'grade')) / count($studentGrades); //to get the average
    array_push($studentAverage, $data);
}

echo json_encode($studentAverage);

http://sandbox.onlinephpfunctions.com/code/ec59112f00b8e54c19176588559ccab325bb90d5

答案 2 :(得分:0)

尝试以下代码:

$student_id_point_gt_100 = [];

foreach ($students as $student){
    if($student['points'] > 100){
        $student_id_point_gt_100[] = $student['id'];
    }
}
$student_list = [];
foreach ($student_id_point_gt_100 as $key=>$id){
    $i = 0;
    $sum = 0;
    foreach ($grades as $grade){
        if($grade['student_id'] == $id){
            $sum += $grade['grade'];
            $i++;
        }
    }

    $student_list[$key]['student_id'] = $id;
    $student_list[$key]['avg'] = $sum / $i;
}
echo"<pre>"; print_r($student_list); die();

输出:

(
    [0] => Array
        (
            [student_id] => 1
            [avg] => 2.5
        )

)

答案 3 :(得分:0)

首先创建一个$ studentsIds数组,您可以在其中存储从学生数组中过滤出来的学生ID。

  $studentsIds = array();

然后将$ students和$ grades数组放入。

  $students = array(
     array(
             'id' => '1',
             'name' => 'Rambo Jhon',
             'tel' => '1234567',
             'email' => 'rambo@duckmail.com',
             'points' => '120',
     ),
     array(
             'id' => '2',
             'name' => 'Donald Duck',
             'tel' => '8562904',
             'email' => 'dduck@duckmail.com',
             'points' => '98',
      )
   );
   $grades = array(
       array(
             'student_id' => '1',
             'course_id' => 'c1',
             'grade' => '2'
       ),
       array(
             'student_id' => '2',
             'course_id' => 'c2',
             'grade' => '4'
       ),
       array(
             'student_id' => '1',
             'course_id' => 'c3',
             'grade' => '3'
       )
   );

然后执行一个foreach循环,并在循环的每次迭代中检查点是否大于100。如果大于100,则将ID存储到$ studentsIds数组中。a

     $i = 0;
     foreach($students as $key => $Value) {
        if($Value['points'] >100) {
           $studentsIds[$i] = $Value['id'];
           echo "ID = ".$studentsIds[$i]."<br>";
           $i++;
        }
     }

因此,这些ID现在有> 100点,您可以在$ studentsIds数组中找到这些ID。最后,再次在$ grades数组上运行foreach循环,并过滤$ studentsIds数组中的$ Value ['student_id']出口。如果退出该ID,则计算平均值。

  foreach($grades as $key => $Value) {
           $my_value = $Value['student_id'];
           $filtered_array = array_filter($studentsIds, function ($element) use ($my_value) {
                 return ($element == $my_value);
               }); 
           if($filtered_array) {
             //calculate your avg grade point
           }  
     }