我有一个对象数组,我想排序。我想根据每个对象的两个值对数组进行排序:
E.g
Array (
[0] => "TeamName time (Id) - CoachName",
[1] => "TeamName time (Id) - CoachName"
...
)
我想先在CoachName
上排序,然后在time
上排序,这样
分拣之前
Array(
[0] => "FirstTeam 12:00-12:30 (1234) - Jack Harper",
[1] => "FirstTeam 12:00-12:30 (5678) - Sofia Jackson",
[2] => "SecondTeam 12:30-13:00 (1122) - Jack Harper",
[3] => "SecondTeam 12:30-13:00 (2211) - Sofia Jackson"
)
分拣后
Array(
[0] => "FirstTeam 12:00-12:30 (1234) - Jack Harper",
[1] => "SecondTeam 12:30-13:00 (1122) - Jack Harper",
[2] => "FirstTeam 12:00-12:30 (5678) - Sofia Jackson",
[3] => "SecondTeam 12:30-13:00 (2211) - Sofia Jackson"
)
您可以使用手工制作的比较函数来提供给PHP的usort函数。
$a = array(
"FirstTeam 12:00-12:30 (1234) - Jack Harper",
"FirstTeam 12:00-12:30 (5678) - Sofia Jackson",
"SecondTeam 12:30-13:00 (1122) - Jack Harper",
"SecondTeam 12:30-13:00 (2211) - Sofia Jackson"
);
function cmpCoachTime($s1, $s2) {
$pattern = '/('d{2}:'d{2}).*? - (['w's]+)/';
preg_match($pattern, $s1, $matches);
$coach1 = $matches[2];
$time1 = strtotime($matches[1]);
preg_match($pattern, $s2, $matches);
$coach2 = $matches[2];
$time2 = strtotime($matches[1]);
$coachCmp = strcmp($coach1, $coach2);
if ($coachCmp == 0) {
if ($time1 == $time2) {
return 0;
}
return $time1 < $time2 ? -1 : 1;
}
return $coachCmp;
}
var_dump($a); // outputs initial array
usort($a, 'cmpCoachTime');
var_dump($a); // ouputs sorted array
对您的输入进行了测试,并获得了所需的输出。
您可以在PHP文档中找到一个示例,使用array_multisort:
链接:http://www.php.net/manual/en/function.array-multisort.php
用法示例:
<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
// Obtain a list of columns
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
排序结果:
volume | edition
-------+--------
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7
我不确定还有其他更好的选择,但这是我发现的第一个:)。
祝你好运,Stefan。
我认为这里的正确结构应该是一个关联数组的数组。。。
[
[
'teamName' => 'FirstTeam',
'startTime' => '12:00',
'endTime' => '12:30',
'id' => '1234',
'coachName' => 'Jack Harper',
],
...
];
排序会容易得多…:-)