如何使用PHP对数组进行排序,忽略文章(a,an,the)?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了如何使用PHP对数组进行排序,忽略文章(a,an,the)?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有以下数组$Books(实际数组更大):
Array
(
    [0] => The Mystic Masseur
    [1] => The Suffrage of Elvira
    [2] => Miguel Street
    [3] => A House for Mr Biswas
    [4] => Mr Stone and the Knights Companion
    [5] => The Mimic Men
    [6] => A Flag on the Island
    [7] => In a Free state
    [8] => Guerrillas
    [9] => A Bend in the River
    [10] => The Enigma of Arrival
    [11] => A Way in the World
    [12] => Half a Life
    [13] => Magic Seeds
)

当我使用sort函数时,结果如下:

Array
(
    [0] => A Bend in the River
    [1] => A Flag on the Island
    [2] => A House for Mr Biswas
    [3] => A Way in the World
    [4] => Guerrillas
    [5] => Half a Life
    [6] => In a Free State
    [7] => Magic Seeds
    [8] => Miguel Street
    [9] => Mr Stone and the Knights Companion
    [10] => The Enigma of Arrival
    [11] => The Mimic Men
    [12] => The Mystic Masseur
    [13] => The Suffrage of Elvira
)

但我想在开头忽略文章(a,an,the),并希望得到这样的结果:

Array
(
    [0] => A Bend in the River
    [1] => The Enigma of Arrival
    [2] => A Flag on the Island
    [3] => Guerrillas
    [4] => Half a Life
    [5] => A House for Mr Biswas
    [6] => In a Free State
    [7] => Magic Seeds
    [8] => Miguel Street
    [9] => The Mimic Men
    [10] => Mr Stone and the Knights Companion
    [11] => The Mystic Masseur
    [12] => The Suffrage of Elvira
    [13] => A Way in the World
)

我试过了:

$_books = array();
foreach($books as $book){
    if(substr($book,4) == "The "){
    $_books[substr($book,4)] = $book;
    }
    else if(substr($book,3) == "An "){
    $_books[substr($book,3)] = $book;
    }
    else if(substr($book,2) == "A "){
    $_books[substr($book,2)] = $book;
    }
    else{
    $_books[$book] = $book;
    }
}
ksort($_books);
$books = array_values($_books);

但我知道这不是最好的解决方案,因为它有丢失价值风险(例如,如果输入中同时存在“A fantasy”和“The Fantasy”,则输出中只会出现“The Fantasy”).那么,什么是最好的解决方案?

使用自定义排序功能
function handleArticles($str) {
    list($First,$rest) = explode(" ",$str." ",2);
       // the extra space is to prevent "undefined offset" notices
       // on single-word tITles
    $validarticles = array("a","an","the");
    if( in_array(strtolower($first),$validarticles)) return $rest.",".$first;
    return $str;
}
usort($books,function($a,$b) {
    return strnatcasecmp(handleArticles($a),handleArticles($b));
});

脚本宝典总结

以上是脚本宝典为你收集整理的如何使用PHP对数组进行排序,忽略文章(a,an,the)?全部内容,希望文章能够帮你解决如何使用PHP对数组进行排序,忽略文章(a,an,the)?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。