【问题标题】:How to sort multidimensional array by secondary array's values如何按辅助数组的值对多维数组进行排序
【发布时间】:2013-10-10 14:31:41
【问题描述】:

我正在尝试对这个多维数组进行排序。我不想按第二个数组中包含的名称对数组的第一个维度进行排序。

我将如何按“名称”的字母顺序对其进行排序:

Array
(
[0] => Array
    (
        ["name"] => "Delta"
        ["other1"] => "other data..."
        ["other2"] => "other data..."
    )

[1] => Array
    (
        ["name"] => "Beta"
        ["other1"] => "other data..."
        ["other2"] => "other data..."
    )

[2] => Array
    (
        ["name"] => "Alpha"
        ["other1"] => "other data..."
        ["other2"] => "other data..."
    )
)

结果是这样的:

Array
(
[0] => Array
    (
        ["name"] => "Alpha"
        ["other1"] => "other data..."
        ["other2"] => "other data..."
    )

[1] => Array
    (
        ["name"] => "Beta"
        ["other1"] => "other data..."
        ["other2"] => "other data..."
    )

[2] => Array
    (
        ["name"] => "Delta"
        ["other1"] => "other data..."
        ["other2"] => "other data..."
    )
)

非常感谢您的帮助!

【问题讨论】:

标签: php arrays


【解决方案1】:

http://3v4l.org/hVUPI

<?php

$array = array(
    array(
        "name" => "Delta",
        "other1" => "other data...",
        "other2" => "other data...",
    ),
    array(
        "name" => "Beta",
        "other1" => "other data...",
        "other2" => "other data...",
    ),
    array(
        "name" => "Alpha",
        "other1" => "other data...",
        "other2" => "other data...",
    ),
);

usort($array, function($a, $b) {
    return strcmp($a['name'], $b['name']);
});

print_r($array);

输出:

Array
(
    [0] => Array
        (
            [name] => Alpha
            [other1] => other data...
            [other2] => other data...
        )

    [1] => Array
        (
            [name] => Beta
            [other1] => other data...
            [other2] => other data...
        )

    [2] => Array
        (
            [name] => Delta
            [other1] => other data...
            [other2] => other data...
        )

)

【讨论】:

  • 嗨!我的回答对你有帮助吗?如果您能接受答案,我将不胜感激。谢谢!
猜你喜欢
  • 2021-07-11
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
相关资源
最近更新 更多