Custom ordering array with key / value pairs
The following array arrives:
Array
(
[66-507cddcd16d9786abafccfa78b19acf8] => XL
[64-507cddcd16d9786abafccfa78b19acf8] => medium
[65-5开发者_运维知识库07cddcd16d9786abafccfa78b19acf8] => large
[63-507cddcd16d9786abafccfa78b19acf8] => small
)
How can I order the values of the array in ascending size order in such a way that the key / value relation is maintained? The array values may be some or all of the following
Small
XXL
Medium
Large
XL
If your sorting needs are more complex than asort
or ksort
as previously suggested, then write a function to plug into uasort
.
You need to use uasort
:
function sizeSorter($a, $b) {
// customize as needed
$comp = array_flip(array('xxxs', 'xxs', 'xs', 's', 'small', 'm', 'medium', 'l', 'large', 'xl', 'xxl', 'xxxl'));
return $comp[strtolower($a)] - $comp[strtolower($b)];
}
uasort($array, 'sizeSorter');
Live example:
http://codepad.org/vxcN29sO
If you want to sort your values alphabetically, that's what asort is for.
you can use asort. I copied this fomr the php website
asort — Sort an array and maintain index association
http://php.net/manual/en/function.asort.php
精彩评论