-4

I have the following array as an example and want to sort the list alphabetically by title.

Array
(
    [0] => Array
        (
            [director] => Alfred Hitchcock
            [title] => Rear Window
            [year] => 1954
        )

    [1] => Array
        (
            [director] =>  Scorsese
            [title] => Mean Streets
            [year] => 1973
        )

    [2] => Array
        (
            [director] =>  Kubrick
            [title] => A Clockwork Orange
            [year] => 1971
        )

    [3] => Array
        (
            [director] => Stanley 
            [title] => Full Metal Jacket
            [year] => 1987
        )

)

2

2 Answers 2

1

You can use usort() function to sort, then strcasecmp() to compare title key

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

print_r($array);
Sign up to request clarification or add additional context in comments.

Comments

0

This is how I would do it. Full working example:

<?php

$arr = [
    [
        'director' => 'Alfred Hitchcock',
        'title' => 'Rear Window',
        'year' => '1954',
    ],
    [
        'director' => 'Scorsese',
        'title' => 'Mean Streets',
        'year' => '1973',
    ],
    [
        'director' =>  'Kubrick',
        'title' => 'A Clockwork Orange',
        'year' => '1971',
    ],
    [
        'director' => 'Stanley',
        'title' => 'Full Metal Jacket',
        'year' => '1987',
    ],
];

usort( $arr, function( $a, $b ){
    if($a['title'] == $b['title']) {
        return 0;
    }
    return ($a['title'] < $b['title']) ? -1 : 1;
});

echo '<pre>';
print_r( $arr );
echo '</pre>';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.