通过在PHP中执行算术运算来更改数组内容的顺序

Changing the order of the array contents by performing arithmetic operations in PHP

本问题已经有最佳答案,请猛点这里访问。

我有以下数组输出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    Array
(
    [0] => Array
        (
            [student_id] => 39
            [scored] => 50
            [out_of] => 100
        )

    [1] => Array
        (
            [student_id] => 40
            [scored] => 80
            [out_of] => 100
        )

)

我要计算学生的百分比,并要显示在上面的学生,他们的百分比更高。我该怎么做?我可以更改数组本身的顺序吗?请帮助

我希望数组是这样的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Array
(
    [0] => Array
        (            
            [student_id] => 40
            [scored] => 80
            [out_of] => 100
        )

    [1] => Array
        (
            [student_id] => 39
            [scored] => 50
            [out_of] => 100
        )

)

  • USORT和一个小的自写比较函数,并完成。有关如何使用的详细信息,请参阅建议的副本。


使用usort

1
2
3
4
5
6
7
usort($array, function($a, $b) {
    // This code will be executed each time two elements will be compared
    // If it returns a positive value, $b is greater then $a
    // If it returns 0, both are equal
    // If negative, $a is greater then $b
    return ($a['scored'] / $a['out_of']) <=> ($b['scored'] / $b['out_of']);
});

有关此函数的详细信息:http://php.net/manual/en/function.usort.php所有PHP排序算法的列表:http://php.net/manual/en/array.sorting.php

请注意,usort将修改数组本身,因此不要使用$array = usort($array, ...)

  • 如果数组包含更多的记录怎么办?这对只有两个记录的数组有效,对吗?
  • 我更新了代码,没有更多的评论。每次比较两个元素时都会调用函数;如果有"1"、"2"和"3",则首先用"1"+"2"调用函数,然后用"1"+"3"调用函数,然后用"1"+"2"调用函数。所以它可以与任何数组一起工作。
  • 谢谢你的回复。我认为USORT在PHP7上的工作方式不同。我使用的是php7,它不会在执行操作后更改数组的顺序。
  • 在我的PHP7项目中,它是这样工作的。更新了源代码,尝试将"-"替换为"<=>"(宇宙飞船操作员-请参阅stackoverflow.com/questions/30365346/&hellip;)


如果你的out_of是100,每次意味着你的scored本身就是百分比。

无论如何,您可以使用下面的代码

1
2
3
4
5
6
7
8
9
10
 function sortByScore($x, $y) {
  return $y['per'] - $x['per'];
 }

 $new_arr = array();
 foreach ($arr as $key => $value) {
     $per = ($value['scored']  / $value['out_of']  ) * 100;
     $value['per'] = $per;
     $new_arr[] = $value;
 }

首先计算百分比,然后按百分比排序

因为你的scored每次都不一样,你的out_of会更多,所以在scored上排序是不可行的。

1
2
 usort($new_arr, 'sortByScore');
 echo"[cc lang="php"]"; print_r($new_arr);

  • 我试过了。我得到了数组中的百分比,但数组的顺序没有改变。它仍然显示了这个记录,上面的百分比越小,下面的百分比越多。
  • 这在php5上有效。我在研究PHP7,它在那里工作。但是谢谢。