Php基于两个值对数组中的对象进行排序

时间:2013-11-27 14:23:43

标签: php arrays sorting

我有一个对象数组,我想排序。我想对每个对象的两个值排序数组:

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"
)

3 个答案:

答案 0 :(得分:2)

您可以使用手工制作的比较功能来提供给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

测试您的输入并获得所需的输出。

答案 1 :(得分:1)

您可以在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

我不确定还有其他/更好的选择,但这是我发现的第一个:)。

祝你好运, 斯蒂芬。

答案 2 :(得分:0)

我认为这里的正确结构将是一个关联数组...

[
    [
        'teamName' => 'FirstTeam',
        'startTime' => '12:00',
        'endTime' => '12:30',
        'id' => '1234',
        'coachName' => 'Jack Harper',
    ],
    ...
];

对它进行排序会更容易......: - )