Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Sort an array by a child array's value in PHP

I have an array composed of arrays. I want to sort the parent array by a property of the child arrays. Here's an example

array(2){
    [0]=> array(3){
        [0]=> string(6) "105945"
        [1]=> string(10) "First name"
        [2]=> float(0.080878465391)
    }
    [1]=> array(3) {
        [0]=> string(6) "109145"
        [1]=> string(11) "Second name"
        [2]=> float(0.0504154818384)
    }
}

I would like to sort the parent array by [2] ascending in the child arrays, so in this case the result would be the child arrays reversed (.05, 08). Is this possible using any of the numerous PHP sort functions?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can make use of usort function as:

$arr = array(
                array("105945","First name",0.080878465391),
                array("109145","Second name",0.0504154818384)
            );

function cmp($a, $b) {
        if ($a[2] == $b[2]) {
                return 0;
        }
        return ($a[2] < $b[2]) ? -1 : 1;
}

usort($arr,"cmp");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...