简体   繁体   English

PHP 以子字符串为标识符对字符串数组进行排序

[英]PHP Sorting String Array With Substring As Identifier

I want to sort an array of strings where the substring I want to use as sorting identifier is in the middle of the string in question.我想对一个字符串数组进行排序,其中我想用作排序标识符的子字符串位于相关字符串的中间。 I've already tried to do that using a very crude technique and I was wondering if there was a better way to do this.我已经尝试使用非常粗糙的技术来做到这一点,我想知道是否有更好的方法来做到这一点。

Here is what I've come up with so far:这是我到目前为止想出的:

<?php
$tracks = array(
"Arcane Library_Track2.mp3",
"Deeper Ocean_Track4.mp3"
"Neon Illumination_Track3.mp3",
"Sound Of Cars_Track1.mp3",
);

$tracksreversed = array();
$sortedtracks = array();

foreach( $tracks as $t) {
    array_push( $tracksreversed, strrev($t) ); 
}

sort($tracksreversed);

foreach( $tracksreversed as $t ) {
    array_push( $sortedtracks, strrev($t) );
}

$tracks = $sortedtracks;
?>

This method works but there are two issues.这种方法有效,但有两个问题。 For one it uses two loops and the second problem is that this method will fail as soon as we include more file types like ogg or wav .首先,它使用两个循环,第二个问题是,一旦我们包含更多文件类型(如oggwav ),此方法就会失败。

Is there a way to easily sort this string according to the _Track1 , _Track2 , _Track3 indentifiers?有没有办法根据_Track1_Track2_Track3轻松地对这个字符串进行排序? Maybe some regex sorting could be done here or perhaps there is some other method I could do which makes this more compact?也许可以在这里完成一些正则表达式排序,或者我可以做一些其他方法使这更紧凑?

Maybe the usort function will be useful.也许usort函数会很有用。 Like:喜欢:

$getIdx = function(string $name) {
   preg_match('/_Track(?<idx>\d+)/', $name, $matches);
   return $matches['idx'];
};

usort($tracks, function ($a, $b) use ($getIdx) {
   return $getIdx($a) <=> $getIdx($b);
});

Seems to work https://3v4l.org/j65rd似乎工作https://3v4l.org/j65rd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM