[英]How to sort multidimensional array in PHP version 5.4?
我有一个数组结构,其print_r
输出如下所示:
Array
(
[0] => Array
(
[0] => Game
[1] => Date
[2] => Site
[3] => Address
[4] => FirstName
[5] => LastName
[6] => Email
[7] => Phone
)
[1] => Array
(
[0] => B-Dry @ Blue Wave DH
[1] => 7/9/2019 13:00
[2] => Blue Wave Dover City Park
[3] => Dover
[4] => John
[5] => Doe
[6] => john.doe@perrylocal.org
[7] => (555) 555-4797
)
[2] => Array
(
[0] => B-Dry @ Blue Wave DH
[1] => 7/9/2019 13:00
[2] => Blue Wave Dover City Park
[3] => Dover
[4] => Frank
[5] => Sinatra
[6] => frank@sinatra.com
[7] => (555) 685-5555
)
[3] => Array
(
[0] => B-Dry @ Gnaden
[1] => 6/7/2019 18:00
[2] => Gnaden Indian Valley HS
[3] => Gnadenhutten
[4] => Jimmy
[5] => Dean
[6] => jimmy@dean.org
[7] => (330) 555-5555
)
[...many more...]
)
数据来自excel电子表格。 如果它来自SQL,排序将是微不足道的。 :-)
我如何排序/重新排序此数组,如下所示:
这篇文章看起来很有希望,但是我相信array_column
仅在PHP 5.5中有效,而我还不能升级到PHP 5.5。 而且我不确定在所有情况下如何排除第一个数组集(列标签)。
这是一个函数,它将根据所需的列数对多维数组进行排序:
function mult_usort(&$arr, $max_index = false, $index = 0) {
// Done on purpose, could not use a closure
function mult_usort_callback($a, $b, $max_index, $index) {
$max_index = $max_index ?: (count($a) - 1);
// Recursive to sort till the max index
if ($a[$index] == $b[$index]) {
if ($index < $max_index) {
return mult_usort_callback($a, $b, $max_index, ($index + 1));
} else {
return 0;
}
}
return $a[$index] > $b[$index] ? 1 : -1;
};
usort($arr, create_function('$a, $b', 'return mult_usort_callback($a, $b, ' . $max_index . ', ' . $index . ');'));
}
并像这样使用它:
// Remove the 1st item
array_shift($data);
// Change the date & time column to DateTime objects for proper comparison
// DateTime: PHP >= 5.2
$data = array_map(function ($item) {
$item[1] = DateTime::createFromFormat('d/m/Y H:i', $item[1]);
return $item;
}, $data);
// Then sort with the function, till index 2
mult_usort($data, 2);
该功能使用:
如果您的数据是SQL查询的结果,则最好在查询中进行ORDER
,这将更加轻松快捷 。
另请参见: 关联数组的更新函数
要摆脱第一个元素,只需:
unset($array[0]);
然后将usort函数与DateTime比较一起使用:
<?php
$data = [
[
'Game',
'Date',
'Site',
'Address',
'FirstName',
'LastName',
'Email',
'Phone'
],
[
'B-Dry @ Gnaden',
'6/7/2019 18:00',
'Gnaden Indian Valley HS',
'Gnadenhutten',
'Jimmy',
'Dean',
'jimmy@dean.org',
'(330) 555-5555'
],
[
'B-Dry @ Blue Wave DH',
'7/9/2019 19:00',
'Blue Wave Dover City Park',
'Dover',
'John',
'Doe',
'john.doe@perrylocal.org',
'(555) 555-4797'
],
[
'B-Dry @ Blue Wave DH',
'7/9/2019 13:00',
'Blue Wave Dover City Park',
'Dover',
'Frank',
'Sinatra',
'frank@sinatra.com',
'(555) 685-5555'
]
];
unset($data[0]);
usort($data, function ($a, $b) {
if ($a[0] == $b[0]) {
$d1 = DateTime::createFromFormat('d/m/y h:i',$a[1]);
$d2 = DateTime::createFromFormat('d/m/y h:i',$b[1]);
if ($d1 == $d2) {
if ($a[2] == $b[2]) {
return 0;
}
return ($a[2] < $b[2]) ? -1 : 1;
}
return ($d1 < $d2) ? -1 : 1;
}
return ($a[0] < $b[0]) ? -1 : 1;
});
var_dump($data, true);
在以下位置检查: https : //3v4l.org/uMacS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.