需要通过循环创建降序

Need to create descending order through loop

我有两个数组。我正在通过循环比较这些数组并计算结果,但它总是按数组索引进行升序排列。我需要在使用这些值按降序计算后创建顺序。

<?php
$correctAnswers = [
['name'=> 1, 'value'=> 4],
['name'=> 1, 'value'=> 1]
];

$submittedStudentData =[
[101, 0, 1, 1],
[102, 0, 4, 1]
];

if(!is_array($submittedStudentData))
{
    $submittedStudentData = json_decode($submittedStudentData);
}


for ($index = 0; $index < count($submittedStudentData); $index++){

   // get each student data
   $studentData = $submittedStudentData[$index];

   // get the student roll number
   $studentId = $studentData[0];


   // initialize the total result with zero pre value
   $totalResult = 0;

// loop through the student's submitted answer
for ($i = 2; $i < count($studentData); $i++) 
{
   if ((int)$studentData[$i] === (int)$correctAnswers[$i - 2]["value"])
  {
    $totalResult++;
  }
}


// final result for this student
echo 'Student with roll number '. $studentId .' scores '. $totalResult."\n";


}
?>

输出为

Student with roll number 101 scores 1
Student with roll number 102 scores 2

我需要按得分降序排列的输出。

Student with roll number 102 scores 2
Student with roll number 101 scores 1

studentIdtotalScores 创建一个数组占位符然后反转数组更容易我认为

<?php
$correctAnswers = [
['name'=> 1, 'value'=> 4],
['name'=> 1, 'value'=> 1]
];

$submittedStudentData =[
[101, 0, 1, 1],
[102, 0, 4, 1]
];

if(!is_array($submittedStudentData))
{
    $submittedStudentData = json_decode($submittedStudentData);
}

$s_data = [];
for ($index = 0, $c = count($submittedStudentData); $index < $c; $index++){

   // get each student data
   $studentData = $submittedStudentData[$index];

   // get the student roll number
   $studentId = $studentData[0];


   // initialize the total result with zero pre value
   $totalResult = 0;

// loop through the student's submitted answer
for ($i = 2, $x = count($studentData) ; $i < $x; $i++) 
{
   if ((int)$studentData[$i] === (int)$correctAnswers[$i - 2]["value"])
  {
    $totalResult++;
  }
}

    $s_data[] = ['studentId' =>$studentId, 'scores'=>$totalResult];

// final result for this student

}

$r = array_reverse($s_data);

foreach($r as $d)
{
    echo 'Student with roll number '. $d['studentId'] .' scores '. $d['scores']."\n";

}
?>

演示:https://3v4l.org/Fgsi9

[编辑] 我忽略了您需要对 score 值进行排序。在这种情况下,您需要比较新数组中的值。

演示:https://3v4l.org/amfBa

在此处 How to Sort a Multi-dimensional Array by Value

了解有关基于数组 key/value 的排序的更多信息