假设您的排序功能确实有效,并假设我对正则表达式真的很不好,我已经实现了一个可以为您完成这项工作的类:
<?php
class sorter {
private $_array = array();
function __construct($array) {
$this->_array = $array;
}
public function elaborate() {
if (preg_match("~([0-9]+|[0-9])~", $this->_array[0])) {
usort ($this->_array, array('sorter','sort_numeric'));
}
else {
if (preg_match("~(?=^(X)(?=(L)$))|(?=^(L)$)|(?=^(M)$)~", $this->_array[0])) {
usort ($this->_array, array('sorter','sort_size'));
}
else {
usort ($this->_array, array('sorter','sort_text'));
}
}
return $this->_array;
}
protected static function sort_numeric($a, $b) {
return $a - $b;
}
protected static function sort_size($a, $b) {
static $sizes = array('XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL');
$asize = 100;
$apos = -1;
$bsize = 100;
$bpos = -1;
foreach ($sizes AS $val => $str) {
if (($pos = strpos($a, $str)) !== FALSE && ($apos < 0 || $pos < $apos)) {
$asize = $val;
$apos = $pos;
}
if (($pos = strpos($b, $str)) !== FALSE && ($bpos < 0 || $pos < $bpos)) {
$bsize = $val;
$bpos = $pos;
}
}
return ($asize == $bsize ? 0 : ($asize > $bsize ? 1 : -1));
}
protected static function sort_text($a, $b) {
static $sizes = array("extra small","small","quite small?","something a bit too small","you surely don't fit there.","medium","big","very big","huge","enormous!");
$asize = 100;
$apos = -1;
$bsize = 100;
$bpos = -1;
foreach ($sizes AS $val => $str) {
if (($pos = strpos($a, $str)) !== FALSE && ($apos < 0 || $pos < $apos)) {
$asize = $val;
$apos = $pos;
}
if (($pos = strpos($b, $str)) !== FALSE && ($bpos < 0 || $pos < $bpos)) {
$bsize = $val;
$bpos = $pos;
}
}
return ($asize == $bsize ? 0 : ($asize > $bsize ? 1 : -1));
}
}
?>
对于你说的“类型 3”,它基本上和类型 2 完全一样,你只需要实现一个包含文本应该包含的元素的数组。
上面代码的用法,下面3个例子:
<?php
$type1 = array("120 cm","100 x 160 cm","10 mm x 30 cm");
$type2 = array("XL","XS","XXL","M");
$type3 = array("very big","small","extra small","something a bit too small");
$sorter = new sorter($type1);
echo "<pre>";
print_r($sorter->elaborate());
echo "</pre>";
$sorter = new sorter($type2);
echo "<pre>";
print_r($sorter->elaborate());
echo "</pre>";
$sorter = new sorter($type3);
echo "<pre>";
print_r($sorter->elaborate());
echo "</pre>";
?>
输出:
Array
(
[0] => 10 mm x 30 cm
[1] => 100 x 160 cm
[2] => 120 cm
)
Array
(
[0] => XS
[1] => M
[2] => XL
[3] => XXL
)
Array
(
[0] => extra small
[1] => small
[2] => something a bit too small
[3] => very big
)
这背后的逻辑很简单:
第一个正则表达式检查数组的第一个元素内是否有任何数字。如果是这样,它会使用 sort_numeric 函数对其进行排序。
第二个正则表达式检查数组的第一个元素是以 X 开头并以 L 结尾还是以 M 或 L 开头并以 M 或 L 结尾(如果我没记错的话,这应该涵盖大多数情况):如果是, 它使用 sort_size 函数,否则使用 sort_text。
工作沙箱:
http://sandbox.onlinephpfunctions.com/code/9362377a481b0f4f2d33ccdfa4347f4e7c005e92