Simon Hagmann
Simon Hagmann

Reputation: 141

Sort Array by Name PHP

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)

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

Thank you

Upvotes: 0

Views: 88

Answers (3)

Syscall
Syscall

Reputation: 19780

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
)

Upvotes: 3

Rahul
Rahul

Reputation: 1615

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

 asort($arr);

asort() - Maintains key association: yes.

Upvotes: 1

J. Doe
J. Doe

Reputation: 1732

$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);

Upvotes: 0

Related Questions