Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

sorting - Sort Multi-Dimensional Array PHP

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
                )

        )

)

I've tried using sort(), asort(), and usort() but nothing does what I need?

Edit: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You might want try usort. It allows you to sort an array specifying a custom callback function. Since you are not clearly stating by what criteria you want to sort your items I can not really help you with the function. (My guess is reverse alphabetically by House_Colour since Red > Green > Blue but I am not sure if you do not have another criteria I overlooked.)

This simple comparison function orders entries by the house color in the order you specified and is easy to modify to what you really want. Each color has a rank you can assign your self (you can also easily add new colors), also you can change the order easily by flipping the comparison-operator in the else if part.

function cmp($a, $b) {
    $colors = Array('RED' => 3, 'GREEN' => 2, 'BLUE' => 1);
    // A is ranked same as B
    if ($colors[$a['House_Colour']] == $colors[$b['House_Colour']]) {
        return 0;
    }
    // A is ranked above B
    else if ($colors[$a['House_Colour']] > $colors[$b['House_Colour']]) {
        return 1;
    }
    // A is ranked below B
    else {
        return -1;
    }
}

You can see a running example here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...