按多个字段对多维数组排序

动力浮标

我发现了一些有关此的问题,但我觉得这里有一个非常特殊的情况,所以我要问一个新问题。

我需要先按用户的标题(数组)然后按姓氏对用户数组进行排序,请考虑以下代码:

<?php
$users = [
    [
        'lastName' => 'Clarks',
        'titles' => ['Manager', 'Supervisor']
    ],
    [
        'lastName' => 'Clarkson',
        'titles' => ['Sales']
    ],
    [
        'lastName' => 'Adams',
        'titles' => ['Supervisor']
    ],
    [
        'lastName' => 'Adams',
        'titles' => ['Manager', 'Senior Manager']
    ],
    [
        'lastName' => 'Clarkson',
        'titles' => ['Manager']
    ],
    [
        'lastName' => 'Davids',
        'titles' => ['Senior Manager']
    ]
];

我想要的顺序是:

<?php
$order = [
    'Senior Manager',
    'Manager',
    'Supervisor'
];

如果有多个管理器,则应按lastName对其进行排序,因此在这种情况下的输出为:

<?php
$sorted = [
    [
        'lastName' => 'Adams',
        'titles' => ['Manager', 'Senior Manager']
    ],
    [
        'lastName' => 'Davids',
        'titles' => ['Senior Manager']
    ],
    [
        'lastName' => 'Clarks',
        'titles' => ['Manager', 'Supervisor']
    ],
    [
        'lastName' => 'Clarkson',
        'titles' => ['Manager']
    ],
    [
        'lastName' => 'Adams',
        'titles' => ['Supervisor']
    ],
    [
        'lastName' => 'Clarkson',
        'titles' => ['Sales']
    ]
];

我已经尝试了以下方法,但是无法使其正常工作,并且发现调试起来有些困难usort

<?php
foreach ($order as $title) {
    usort($users, function ($a, $b) use ($title) {
        # Both have the title
        if (in_array($title, $a['titles']) and in_array($title, $b['titles']) ) {
            # Sort by name
            return strcmp($a['lastName'], $b['lastName']);
        }
        # A has the title
        elseif (in_array($title, $a['titles'])) {
            return 1;
        }
        # B has the title
        elseif (in_array($title, $b['titles'])) {
            return -1;
        }

        # No-one has the title
        return strcmp($a['lastName'], $b['lastName']);
    });
}
弗雷德里克·容格斯特

您想要的是根据中标题最低索引用户进行排序$order您可以利用array_search来找到他们每个书名的索引,$order并使用查找最低的书名min如果它们相同,则退回到strcmp

usort($users, function($a, $b) use ($order) {
    $minAPos = min(array_map(function($title) use ($order) {
        $pos = array_search($title, $order);
        return $pos === false? sizeof($order) : $pos;
    }, $a['titles']));
    $minBPos = min(array_map(function($title) use ($order) {
        $pos = array_search($title, $order);
        return $pos === false? sizeof($order) : $pos;
    }, $b['titles']));

    if($minAPos === $minBPos) {
        return strcmp($a['lastName'], $b['lastName']);
    } else {
        return $minAPos <=> $minBPos;
    }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章