Custom sort array in PHP [duplicate]
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!
精彩评论