【问题标题】:Sorting alphabetically by Array Value in Multidimensional Indexed Array After Custom Sort (usort) / Sort Array by Two Values自定义排序(usort)/按两个值排序数组后按多维索引数组中的数组值字母顺序排序
【发布时间】:2020-12-27 14:56:04
【问题描述】:

原始数组:

[0] => Array
    (
        [name] => Light Amethyst
        [description] => color
    )

[1] => Array
    (
        [name] => Stone
        [description] => base material
    )

[2] => Array
    (
        [name] => Emerald
        [description] => color
    )

[3] => Array
    (
        [name] => Brass
        [description] => base material
    )

通过以下函数应用usort($terms, "mysort");

function getSortOrder($c) {
    $sortOrder = array(
        "base material",
        "color"
    );
    $pos = array_search($c['description'], $sortOrder);
    return $pos !== false ? $pos : 99999;
}

function mysort($a, $b) {
    if( getSortOrder($a) < getSortOrder($b) ) {
        return -1;
    }elseif( getSortOrder($a) == getSortOrder($b) ) {
        return 0;
    }else {
        return 1;
    }
}

这成功通过getSortOrder函数中的$sortOrder数组排序数组(先基材,后颜色)

[0] => Array
    (
        [name] => Stone
        [description] => base material
    )

[1] => Array
    (
        [name] => Brass
        [description] => base material
    )

[2] => Array
    (
        [name] => Light Amethyst
        [description] => color
    )

[3] => Array
    (
        [name] => Emerald
        [description] => color
    )

现在我正在尝试按name 对这个新的排序数组进行排序,同时保持之前应用的排序顺序(首先是基础材料,然后是颜色)。

预期输出:

[0] => Array
    (
        [name] => Brass
        [description] => base material
    )

[1] => Array
    (
        [name] => Stone
        [description] => base material
    )

[2] => Array
    (
        [name] => Emerald
        [description] => color
    )

[3] => Array
    (
        [name] => Light Amethyst
        [description] => color
    )

通常我可以像这样应用usort 函数:

usort($people,"sort_name");
function sort_name($a,$b)
{
  return $a["name"] > $b["name"];
}

但这当然会弄乱原始 description 排序的输出。

如何像上面的函数一样先按description 排序,然后继续按name 排序,同时保持description 排序不变?

【问题讨论】:

    标签: php arrays sorting multidimensional-array


    【解决方案1】:

    您可以使用array_multisort 一次性将原始数据排序到预期的输出(首先按描述排序,然后按名称排序)

    $data = [
        ['name' => 'Light Amethyst', 'description' => 'color'],
        ['name' => 'Stone', 'description' => 'base material'],
        ['name' => 'Emerald', 'description' => 'color'],
        ['name' => 'Brass', 'description' => 'base material']
    ];
    
    
    array_multisort(array_column($data, 'description'), SORT_ASC, array_column($data, 'name'), SORT_ASC, $data);
    

    $data 现在将按description 第一和name 第二排序。

    【讨论】:

    • 哇!完美运行(并且不需要任何自定义排序功能——没想到会这样)-谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2023-04-02
    • 2011-07-28
    相关资源
    最近更新 更多