【问题标题】:PHP - Sorting multi dimensional arrayPHP - 对多维数组进行排序
【发布时间】:2016-09-27 02:09:27
【问题描述】:

我有一个多维数组

Array
 (
[M] => Array
    (
        [0] => Array
            (
                [first] => Paul
                [last] => Martha
                [progress] => 100
                [id] => 85162
                [category] => M
            )

        [1] => Array
            (
                [first] => Bob
                [last] => Marley
                [progress] => 47
                [id] => 846523
                [category] => M
            )

    )

[M~F1] => Array
    (
        [0] => Array
            (
                [first] => Kenneth
                [last] => Rodriguez
                [progress] => 42
                [id] => 110273
                [category] => M~F1
            )

        [1] => Array
            (
                [first] => Jenifer
                [last] => Lopez
                [progress] => 0
                [id] => 485623
                [category] => M~F1
            )

    )

)

但是,我希望每个较小的数组根据其中的数组中的键按字母顺序对自己进行排序。以数组 M 为例。我希望 PHP 通过按字母顺序排列姓氏组件来组织其子组件。因此,数组 M 将通过按字母顺序排列子数组的子数组来组织其子数组。完成后,它应该如下所示:

Array
(
[M] => Array
    (
    [0] => Array
            (
                [first] => Bob
                [last] => Marley
                [progress] => 47
                [id] => 846523
                [category] => M
            )

        [1] => Array
            (
                [first] => Paul
                [last] => Martha
                [progress] => 100
                [id] => 85162
                [category] => M
            )

    )

[M~F1] => Array
    (
        [0] => Array
            (
        [first] => Jenifer
                [last] => Lopez
                [progress] => 0
                [id] => 485623
                [category] => M~F1
            )

        [1] => Array
            (
                [first] => Keneth
                [last] => Rodriguez
                [progress] => 42
                [id] => 110273
                [category] => M~F1
            )

    )

)

因此,回顾一下,我需要通过查看 subsubsub 数组、收集其 [last] 键并根据 subsubsub 数组的 [last] 键的字母顺序对 subsub 数组进行排序来组织 subsub 数组。

【问题讨论】:

标签: php arrays sorting multidimensional-array alphabetical


【解决方案1】:

让你定义的数组为 $x。

// first, define our comparison function
$cmp = function ($a, $b) {
  // sort by last name, first name
  $a = trim($a['last'] . ' ' . $a['first']);
  $b = trim($b['last'] . ' ' . $b['first']);
  return strcmp($a, $b);
};
foreach ($x as &$subx) {
  // initialize sub array with reference
  usort($subx, $cmp);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多