3

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"?

0

2 Answers 2

7

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>';
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I just updated it to use array_search instead. :)
3

Yes check out this documentation on usort()

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

1 Comment

Links support a good answer but don't constitute a good answer in solitude. Please improve this post. Stack Exchange doesn't want to be a traffic router, it wants to be the last stop for researchers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.