douwen1901
douwen1901
2018-05-02 08:31

按名称PHP排序数组

  • sorting
  • php
  • arrays
已采纳

I have this associative array that I want to sort in a custom order (not just alphabetically):

$arr = [
    '1' => 'Lorem Ipsum 1',
    '2' => 'Lorem Ipsum 3',
    '3' => 'Lorem Ipsum 2',
    '4' => 'Text A',
    '5' => 'Text B',
    '6' => 'Text C',
    '7' => 'Lorem Ipsum 4',
    '8' => 'Text D',
    '9' => 'Text E',
];

I need this output:

$arr = [
    '4' => 'Text A',
    '5' => 'Text B',
    '6' => 'Text C',
    '8' => 'Text D',
    '9' => 'Text E',
    '1' => 'Lorem Ipsum 1',
    '3' => 'Lorem Ipsum 2',
    '2' => 'Lorem Ipsum 3',
    '7' => 'Lorem Ipsum 4'
];

How the array needs to be sorted (keep key-value association)

  • Sort Array Alphabetically
  • After this, all values that start with Text have to be on top

I already tried it with the function uasort, but could not find out how to sort them starting with Text.

Thank you

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongmi1995 dongmi1995 3年前

    You can use uasort(), and in the sort function, check if the value starts by "Text". If so, sort using this case, otherwise, sort naturally:

    $arr = [
        '1' => 'Lorem Ipsum 1',
        '2' => 'Lorem Ipsum 3',
        '3' => 'Lorem Ipsum 2',
        '4' => 'Text A',
        '5' => 'Text B',
        '6' => 'Text C',
        '7' => 'Lorem Ipsum 4',
        '8' => 'Text D',
        '9' => 'Text E',
    ];
    uasort($arr, function($a, $b){
        $a_text = strpos($a, 'Text') === 0;
        $b_text = strpos($b, 'Text') === 0;
        if ($a_text != $b_text) {
            return $b_text - $a_text ;
        }
        return strnatcmp($a,$b);
    });
    print_r($arr);
    

    Output:

    Array
    (
        [4] => Text A
        [5] => Text B
        [6] => Text C
        [8] => Text D
        [9] => Text E
        [1] => Lorem Ipsum 1
        [3] => Lorem Ipsum 2
        [2] => Lorem Ipsum 3
        [7] => Lorem Ipsum 4
    )
    
    点赞 评论 复制链接分享
  • dongmangsha7354 dongmangsha7354 3年前

    use asort. http://php.net/manual/en/function.asort.php.

     asort($arr);
    

    asort() - Maintains key association: yes.

    点赞 评论 复制链接分享
  • du9757 du9757 3年前
    $arr = [
            '1' => 'Lorem Ipsum 1',
            '2' => 'Lorem Ipsum 3',
            '3' => 'Lorem Ipsum 2',
            '4' => 'Text A',
            '5' => 'Text B',
            '6' => 'Text C',
            '7' => 'Lorem Ipsum 4',
            '8' => 'Text D',
            '9' => 'Text E',
        ];
    
        rsort($arr);
        var_dump($arr);
    
    点赞 评论 复制链接分享