简体   繁体   English

PHP按嵌套值按字母顺序对2d数组排序

[英]PHP sort 2d array alphabetically by nested value

I have a PHP array that looks like this: 我有一个看起来像这样的PHP数组:

Array{
    [0] {
        'id'       => '0',
        'title'    => 'foo',
        'address'  => '123 Somewhere',
    }
    [1] {
        'id'       => '1',
        'title'    => 'bar',
        'address'  => '123 Nowhere',
    }
    [2] {
        'id'       => '2',
        'title'    => 'barfoo',
        'address'  => '123 Elsewhere',
    }
    [3] {
        'id'       => '3',
        'title'    => 'foobar',
        'address'  => '123 Whereabouts',
    }
}

and I want to sort it by the 'title' key in the nested arrays, to look like this: 我想通过嵌套数组中的“ title”键对其进行排序,如下所示:

Array{
    [1] {
        'id'       => '1',
        'title'    => 'bar',
        'address'  => '123 Nowhere',
    }
    [2] {
        'id'       => '2',
        'title'    => 'barfoo',
        'address'  => '123 Elsewhere',
    }
    [0] {
        'id'       => '0',
        'title'    => 'foo',
        'address'  => '123 Somewhere',
    }
    [3] {
        'id'       => '3',
        'title'    => 'foobar',
        'address'  => '123 Whereabouts',
    }
}

The first level key values don't matter since I'm keeping track of each nested array via the nested key 'id'. 一级键值无关紧要,因为我通过嵌套键“ id”来跟踪每个嵌套数组。

I've played with ksort() but with no success. 我玩过ksort(),但没有成功。

You should use usort() (i'm assuming PHP 5.3+ here): 您应该使用usort()(我在这里假设PHP 5.3+):

usort($your_array, function ($elem1, $elem2) {
     return strcmp($elem1['title'], $elem2['title']);
});

Edit: I hadn't noticed you wanted to preserve index association, so you actually need to use uasort() instead, with the same parameters. 编辑:我没有注意到您要保留索引关联,因此实际上您需要使用具有相同参数的uasort()来代替。

Edit2: Here is the pre-PHP 5.3 version: Edit2:这是PHP 5.3之前的版本:

function compareElems($elem1, $elem2) {
    return strcmp($elem1['title'], $elem2['title']);
}

uasort($your_array, "compareElems");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM