gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:28:03 25 4
gpt4 key购买 nike

我有一个字体名称数组,这些名称根据宽度来计算,然后根据粗细(按字母顺序)来计算。标准 width 在字符串中没有像其他宽度那样的指示符(压缩、扩展等)。这是我得到它时数组的样子:

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", "Standard", "Condensed"];
// 9 items need 4 bits to be represented:
// ( 0 => 0000 => "Black", ... 8 => 1000 => "ExtraLight" )
$crit2 = ["Black", "ExtraBold", "Bold", "SemiBold", "Medium", "Regular", "Light", "Thin", "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

关于PHP按多个条件自定义排序字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41600847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com