Php 按日期列对多维数组排序,如果日期相同,则使用其他列值

Php 按日期列对多维数组排序,如果日期相同,则使用其他列值,php,arrays,multidimensional-array,sorting,Php,Arrays,Multidimensional Array,Sorting,我有一个多维数组来存储人 Array ( id93294 => array ( Name => "Tom Anderson", Birthday => "03/17/1975", Hometown => 'St. Louis', CurrentLocation => 'Mars' ), id29349 => (array ( Name

我有一个多维数组来存储人

Array (
   id93294 => array (
       Name => "Tom Anderson",
       Birthday => "03/17/1975",
       Hometown => 'St. Louis',
       CurrentLocation => 'Mars'
   ),
   id29349 => (array (
       Name => "Tom Anderson",
       Birthday => "03/17/1975",
       Hometown => 'New York',
       CurrentLocation => 'New York'
   )
)
有点像这样,除了为人们提供更多信息,所以我想先按生日排序,然后按另一个属性排序(如果他们的家乡与他们当前的位置匹配),但一旦我对数组进行第二次排序,它就会丢失我使用生日进行的第一次排序

如何进行多次排序而不破坏以前的排序

另外,我正在使用uasort。

更新 我最近在关于多维数组排序的“确定”主题中以一种更有效的方式回答了这个问题。您可以放心地跳过阅读本答案的其余部分,直接按照链接查找功能更强的解决方案

原始答案 函数
uasort
允许您定义自己的比较函数。简单地把所有你想要的标准放在里面

例如,要按生日排序,然后按姓名排序:

function comparer($first, $second) {
    // First see if birthdays differ
    if ($first['birthday'] < $second['birthday']) {
        return -1;
    }
    else if ($first['birthday'] > $second['birthday']) {
        return 1;
    }

    // OK, birthdays are equal. What else?
    if ($first['name'] < $second['name']) {
        return -1;
    }
    else if ($first['name'] > $second['name']) {
        return 1;
    }

    // No more sort criteria. The two elements are equal.
    return 0;
}
然后你可以做:

uasort($myArray, make_comparer('birthday', 'name'));
这个例子可能太聪明了;一般来说,我不喜欢使用不按名称接受参数的函数。但是在这种情况下,使用场景是一个非常有力的理由,说明它太聪明了。

很好的问题

此伪代码来自您给出的问题定义,旨在作为
uasort
的回调函数。我无法填写详细信息,因为您省略了正在使用的代码;希望这能引导你走上正确的轨道

function compare(p1, p2):
    if birthdays of p1 and p2 are not the same
        compare by birthday
    else
        compare by hometown

如果有人能在评论中验证这是排序算法的有效比较函数,我将不胜感激。

多年后,PHP7+提供了一种更干净、更简洁的技术……宇宙飞船操作员和平衡的“标准”数组

代码:()

uasort($array,function($a,$b){
return[strotime($a['birth']),$a['homightry']!==$a['CurrentLocation'],$a['Name']]
[strotime($b[‘生日’]),$b[‘家乡’!==$b[‘当前位置’],$b[‘姓名’];
});
var_导出($数组);
有关示例输入和输出,请参见演示链接

此代码段将按以下方式排序:

  • 那么生日呢
  • 家乡===CurrentLocation before not===then
  • 名称ASC
  • 注意:#2有
    ==语法仅因为
    false
    求值被视为0,而
    true
    求值被视为1


    如果您需要更改任何条件的任何排序顺序,只需在相应元素处交换
    $a
    $b

    不进行连续排序;正确定义排序函子以考虑树的所有层。
    function compare(p1, p2):
        if birthdays of p1 and p2 are not the same
            compare by birthday
        else
            compare by hometown
    
    uasort($array, function($a, $b) {
        return [strtotime($a['Birthday']), $a['Hometown'] !== $a['CurrentLocation'], $a['Name']]
               <=>
               [strtotime($b['Birthday']), $b['Hometown'] !== $b['CurrentLocation'], $b['Name']];
    });
    var_export($array);