排序多维数组PHP [英] Sort Multi-Dimensional Array PHP
问题描述
如何对以下数组进行排序,以便对房屋进行红色,绿色和蓝色的排序(乔治:位置0,史蒂夫:位置[1],弗雷德:位置[2])?
How do I sort the following array so that the houses are sorted Red, Green and Blue (George: Position 0, Steve: Position [1], and Fred: Position [2])?
Array
(
[catOne] => Array
(
[0] => Array
(
[Opponent] => Steve
[House_Colour] => Green
)
[1] => Array
(
[Opponent] => Fred
[House_Colour] => Blue
)
[2] => Array
(
[Opponent] => George
[House_Colour] => Red
)
)
[catTwo] => Array
(
[0] => Array
(
[Opponent] => Peter
[House Colour] => Green
)
)
)
我尝试使用sort(),asort()和usort(),但我什么都不需要呢?
I've tried using sort(), asort(), and usort() but nothing does what I need?
编辑:排序必须能够轻松更改.它可以是房屋颜色的任何顺序.所使用的顺序只是一个例子.
The sorting needs to be able to be changed easily. It can be in any order of House colour. The order used is just an example.
推荐答案
If I understand what you need to do, you can use usort:
usort($array, function($a, $b) {
$sort = array('Red', 'Green', 'Blue');
if (array_search($a['House_Colour'], $sort) > array_search($b['House_Colour'], $sort)) return 1;
if (array_search($a['House_Colour'], $sort) < array_search($b['House_Colour'], $sort)) return -1;
return 0;
});
如果您可以依靠定义而不是依靠字符串来获得房屋颜色,那么解决方案将更加简单高效.
If you can leverage on defines instead on relying on strings for the house colors the solutions will be straiforward and more efficient.
您应该在静态类中定义房屋颜色(以模拟枚举类型)
You should define the House colors in a static class (to simulate an enumerated type)
Class HouseColour {
const Red = 0;
const Green = 1;
const Blue = 2;
}
在这种情况下,您必须声明一个对手/玩家
In this case you have to declare an opponent/player
$opponent = array ( 'Opponent'=>'Steve', 'House_Colour'=>HouseColour::Green);
如果您对类和静态常量不满意(因为这样做确实很棒,您应该对它们感到不满意),则可以采用一系列定义
If you are non confortable with class and static constants (you should be confortable with them as the benefits are really great) you can resort to a sequence of defines
define ('HC_Red',0);
define ('HC_Green', 1);
define ('HC_Blue', 2);
成为对手
$opponent = array ( 'Opponent'=>'Steve', 'House_Colour'=>HC_Green);
在两种情况下,usort函数都相同:
in both cases the usort function is the same:
usort($array, function($a, $b) {
if ($a['House_Colour'] > $b['House_Colour']) return 1;
if ($a['House_Colour'] < $b['House_Colour']) return -1;
return 0;
});
这篇关于排序多维数组PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!