简体   繁体   English

PHP:对字母数组进行排序,以使“ A”为最高,而“ Z”为最低

[英]PHP: sort alphabetical array so that 'A' is highest and 'Z' is lowest

I have an array that is populated with 4 alphabetical letters from 'A' to 'Z'. 我有一个数组,其中填充了从'A'到'Z'的4个字母。 I'm trying to find the lowest value where 'Z' is the lowest and 'A' the highest (like a grading system). 我试图找到最低值,其中“ Z”是最低值,“ A”是最高值(例如评分系统)。 For example: 例如:

$abc = ['A', 'G', 'Y', 'B'];

In this case Y is the lowest grade, but obviously min() and max() won't work since they give me the opposite of what I'm looking for. 在这种情况下,Y是最低的成绩,但是显然min()max()无效,因为它们给了我与我所寻找的相反的东西。 Is there a way to do it in PHP without writing my own function? 有没有一种方法可以在PHP中完成而无需编写自己的函数?

$m = array('A', 'G', 'Y', 'B');
asort($m);
print_r($m); //outpu: Array ( [0] => A [3] => B [1] => G [2] => Y ) 

Solution using array_shift() and array_pop() . 使用array_shift()array_pop()解决方案。 Credit to: Jeremy Ruten 归功于Jeremy Ruten

$abc = array('A', 'G', 'Y', 'B');
asort($abc);
print_r($abc); // Array ( [0] => A [3] => B [1] => G [2] => Y ) 
$highest = array_shift($abc);
$lowest = array_pop($abc);
echo "Highest: $highest. Lowest: $lowest"; // Highest: A. Lowest: Y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM