Search code examples
phparraysusort

Sorting an array by text of first subarray in each row


I have an array stored as $product_categories. A sample of this array is:

$array = [
    [
        ['id' => 10, 'text' => 'Latex'],
        ['id' => 15, 'text' => 'Occasion Latex'],
        ['id' => 82, 'text' => 'Christmas'],
    ],
    [
        ['id' => 11, 'text' => 'Accessories'],
        ['id' => 97, 'text' => 'Retail Accessories'],
        ['id' => 558, 'text' => 'Super Stuffer'],
    ],
    [
        ['id' => 374, 'text' => 'Party Supplies'],
        ['id' => 1488, 'text' => 'Party by Occasion'],
        ['id' => 1493, 'text' => 'Christmas'],
    ],
];

I want to sort it ONLY by the key 'text' in [0], which would give me a result of

[
    [
        ['id' => 11, 'text' => 'Accessories'],
        ['id' => 97, 'text' => 'Retail Accessories'],
        ['id' => 558, 'text' => 'Super Stuffer'],
    ],
    [
        ['id' => 10, 'text' => 'Latex'],
        ['id' => 15, 'text' => 'Occasion Latex'],
        ['id' => 82, 'text' => 'Christmas'],
    ],
    [
        ['id' => 374, 'text' => 'Party Supplies'],
        ['id' => 1488, 'text' => 'Party by Occasion'],
        ['id' => 1493, 'text' => 'Christmas'],
    ],
];

I've tried using

$product_categories = usort($product_categories, 'sortAlphabetically');

function sortAlphabetically($a, $b) {
    return strcmp($a['text'], $b['text']);
}

Using that, a print_r() of the array simply returns 1.

I thought usort() was the correct way to sort the array but clearly I'm doing something wrong here.


Solution

  • You only need to access the subarray data using array syntax as you've expressed in English. (Demo)

    usort(
        $array,
        function($a, $b) {
            return $a[0]['text'] <=> $b[0]['text'];
        }
    );
    var_export($array);
    

    Or in PHP7.4 or higher:

    usort($array, fn($a, $b) => $a[0]['text'] <=> $b[0]['text']);