加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP按多个条件自定义排序字符串数组

发布时间:2020-12-13 16:08:42 所属栏目:PHP教程 来源:网络整理
导读:我有一系列字体名称,就宽度而言,然后就重量而言(按字母顺序).标准宽度在字符串中没有像其他宽度那样的指示符(压缩,扩展等).这是我得到它时阵列的样子: Array ( [0] = Bold [1] = ExtraBold [2] = ExtraLight [3] = Light [4] = Medium [5] = Regular [6] =
我有一系列字体名称,就宽度而言,然后就重量而言(按字母顺序).标准宽度在字符串中没有像其他宽度那样的指示符(压缩,扩展等).这是我得到它时阵列的样子:

Array ( 
[0] => Bold 
[1] => ExtraBold 
[2] => ExtraLight 
[3] => Light 
[4] => Medium 
[5] => Regular 
[6] => SemiBold 
[7] => Thin 
[8] => Condensed Bold 
[9] => Condensed ExtraBold 
[10] => Condensed ExtraLight 
[11] => Condensed Light 
[12] => Condensed Medium 
[13] => Condensed Regular 
[14] => Condensed SemiBold 
[15] => Condensed Thin 
[16] => Expanded Black 
[17] => Expanded Bold 
[18] => Expanded ExtraBold 
[19] => Expanded ExtraLight 
[20] => Expanded Light 
[21] => Expanded Medium 
[22] => Expanded Regular 
[23] => Expanded SemiBold 
[24] => Expanded Thin)

我需要先根据此宽度顺序对其进行排序:

$order_array_crit_one = array("Expanded","Standard","Condensed");

然后根据这个顺序的重量:

$order_array_crit_two = array("Black","ExtraBold","Bold","SemiBold","Medium","Regular","Light","Thin","ExtraLight");

我使用比较单词(like this)的排序函数来解决这个问题,但到目前为止我提出的每个解决方案都是庞大而混乱的.

解决方法

太复杂的比较问题在于它使得usort效率不高,因为它必须多次转换和评估项目.但是,如果以前使用基本排序方式转换数组,则可以减少此工作.一个想法是重建数组,但这次使用计算的数字键:

// 3 items need 2 bits to be represented:
// ( 0 => 00 => "Expanded",1 => 01 => "Standard",2 => 10 => "Condensed" )
$crit1 = ["Expanded","Condensed"];
// 9 items need 4 bits to be represented:
// ( 0 => 0000 => "Black",... 8 => 1000 => "ExtraLight" )
$crit2 = ["Black","ExtraLight"];
// if you join all the bits,each item of your array can be represented with a 6
// bits number:
// ( 0 => 000000 => "Expanded Black" ... 40 => 101000 => "Condensed ExtraLight" )

$crit2 = array_flip($crit2);

$result = [];

foreach ($arr as $item) {
    if (false !== strpos($item,"Expanded"))
        $key = 0;  // 000000
    elseif (false !== strpos($item,"Condensed"))
        $key = 32; // 100000
    else
        $key = 16; // 010000

    $parts = explode(' ',$item);
    $weight = isset($parts[1]) ? $parts[1] : $parts[0];
    $key += $crit2[$weight];

    $result[$key] = $item;
}

ksort($result,SORT_NUMERIC);
$result = array_values($result);

print_r($result);

demo

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读