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

)
JasonB
  • 6,243
  • 2
  • 17
  • 27
ravneet
  • 471
  • 2
  • 5
  • 11
  • 2
    https://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value – hungrykoala Jan 10 '18 at 07:26
  • 3
    *Please response as soon as possible*, I would reply to that, please go **read** as soon as possible [this guide](https://stackoverflow.com/help/asking) – Paul Karam Jan 10 '18 at 07:29

2 Answers2

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);
Luffy
  • 1,028
  • 5
  • 13
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>';
Brian Gottier
  • 4,522
  • 3
  • 21
  • 37