这个问题一直困扰着我,所以我想出了另一个选择。这是一个通用且可重用的解决方案,适用于任何标准。 (至少我能想到的。)你可以找到demo here。
<?php
/**
* Sorts an array based on matching multiple criteria.
*
* Given:
* $array => ['big cat', 'small dog', 'big dog', 'small cat']
* $criteria => [['dog','cat'], ['big','small']]
*
* Result: (biggest to smallest)
* ['big dog', 'small dog', 'big cat', 'small cat']
*/
function multi_sort(&$array, $criteria, $defaults=array()){
$cache = array();
// prepare the criteria by sorting them from longest to shortest
// maintaining the original key (index)
foreach($criteria as &$c){
uasort($c, function($a,$b){
return strlen($b) - strlen($a);
});
}
// define a function for returning the index matching the given str
// given: 'one' and ['zero', 'one', 'two'] returns 1
$findIndex = function($str, $values){
foreach($values as $index=>$value){
if( stripos($str, $value) !== FALSE ){
return $index;
}
}
return NULL;
};
// define a function to calculate a weighted value based on the criteria
// returns a value similar to: 2000-0000-3300 (one segment for each criteria)
$calculateValue = function($str) use ($criteria, $findIndex, $defaults, $cache){
if( !isset($cache[$str]) ){
$parts = array();
foreach($criteria as $i=>$c){
$parts[$i] = $findIndex($str, $c);
if( $parts[$i] === NULL ){
$parts[$i] = (isset($defaults[$i]) ? $defaults[$i] : 1000);
}
$parts[$i] = str_pad($parts[$i], 4, '0');
}
$cache[$str] = implode($parts, '-');
}
return $cache[$str];
};
// define our compare function
$compare = function($a, $b) use ($calculateValue){
$av = $calculateValue($a);
$bv = $calculateValue($b);
return $av > $bv;
};
// sort the array`
usort($array, $compare);
}
$list = array(
'Bold', 'ExtraBold', 'ExtraLight', 'Light', 'Medium', 'Regular', 'SemiBold', 'Thin', 'Condensed Bold', 'Expanded Black', 'Condensed ExtraLight', 'Expanded Thin'
);
// create our sort criteria.
$sort_criteria = array(
array("Expanded", "Standard", "Condensed"),
array("Black", "ExtraBold", "Bold", "SemiBold", "Medium", "Regular", "Light", "Thin", "ExtraLight")
);
// sort our array; default for criteria 1 is 1 (i.e. Standard)
multi_sort($list, $sort_criteria, array(1));
print_r($list);
// lets sort some animals from biggest to smallest.
$animals = ['big cat', 'small dog', 'big dog', 'small cat'];
$sort_criteria = [['dog','cat'], ['big','small']];
multi_sort($animals, $sort_criteria);
print_r($animals);