开发者

Custom sort array in PHP [duplicate]

This question already has answers here: Clo开发者_如何学Gosed 11 years ago.

Possible Duplicate:

How can I sort arrays in php by a custom alphabet?

For example, i have six words:

banana, apple, love, zasca, japanese, car

Is there a way to sort in alphabetic order, using this custom order: "j, c, z, l, a"?


Here's some rough code to get you started:

Basically, it looks at the first letter of each word in the data array, the checks its position in the $sortOrder array. Letters that aren't in $sortOrder get put onto the end in the order appear.

Right off the bat, this is going to break if $sortOrder has more than 100,000 items in it. There are probably other holes too but I figure it's a decent enough example of how usort() works.

<?php
function getSortOrder($c) {
    $sortOrder = array("j","c","z","l","a");
    $pos = array_search($c, $sortOrder);

    return $pos !== false ? $pos : 99999;
}

function mysort($a, $b) {
    if( getSortOrder($a[0]) < getSortOrder($b[0]) ) {
        return -1;
    }elseif( getSortOrder($a[0]) == getSortOrder($b[0]) ) {
        return 0;
    }else {
        return 1;
    }
}

$data = array(
    "banana",
    "apple",
    "love",
    "zasca",
    "japanese",
    "car"
);

echo '<pre>' . print_r($data,true) . '</pre>';
usort($data, "mysort");
echo '<pre>' . print_r($data,true) . '</pre>';
?>


Yes check out this documentation on usort()

Edit: Sorry I gave you key sort but you want to compare values!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜