gpt4 book ai didi

php - 字符串前的多排序数字

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

我想知道如何在字符串之前对数字进行排序。我使用 array_multisort 对数组进行排序。

这是我的示例数据

$arr = [
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => 1
],
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => '2-03'
],
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => 3
],
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => '2-01'
],
];

排序后的当前结果。字符串数字“2-01”在 1 和 3 之间排序

$arr = [
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => 1
],
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => '2-01'
],
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => '2-03'
],
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => 3
],
];

我的预期结果。我想在数字 1 和 3 之后对字符串 '2-01'、'2-03' 进行排序

$arr = [
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => 1
],
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => 3
],
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => '2-01'
],
[
'company_name' => '',
'expiryDate' => '2018.7',
'classification' => '2-03'
],
];

我的排序字段。我使用 array_multisort 对多个字段进行排序

$sortFields = [
'classification' => SORT_ASC,
'company_name' => SORT_ASC,
'expiryDate' => SORT_ASC
];

最佳答案

试试usort()和一个比较器:

// @param $arr array that you want to sort
// @param $sortby sort by $arr[$indexOfArray][$sortby]
// @param $isDate boolean
function sortItOutYourself(&$arr, $sortby, $isDate) {
usort($arr, function($a1, $a2) use ($sortby, $isDate) {
if($isDate)
return DateTime::createFromFormat("Y.m", $a1[$sortby])->getTimestamp()
- DateTime::createFromFormat("Y.m", $a2[$sortby])->getTimestamp();

if( (gettype($a1[$sortby]) == "string" && gettype($a2[$sortby]) == "string") ||
(gettype($a1[$sortby]) == "integer" && gettype($a2[$sortby]) == "integer") )
return $a1[$sortby] > $a2[$sortby] ? 1 : -1;

return gettype($a1[$sortby]) == "integer" && gettype($a2[$sortby]) == "string" ? -1 : 1;
});
}

sortItOutYourself($arr, "classification", false);
sortItOutYourself($arr, "company_name", false);
sortItOutYourself($arr, "expiryDate", true);

关于php - 字符串前的多排序数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759189/

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