midz
midz

Reputation: 65

Sort multidimensional array by two strings

I have the following array that I need to have sorted by name([0]) and platform ([2])

Array
(
[0] => Array
    (
        [0] => Assassins Creed: Syndicate
        [1] => 199
        [2] => PC
        [3] => 1
    )

[1] => Array
    (
        [0] => Assassins Creed: Syndicate
        [1] => 199
        [2] => XONE
        [3] => 1
    )

[2] => Array
    (
        [0] => Assassins Creed: Syndicate
        [1] => 199
        [2] => PC
        [3] => 1
    )
)

I already have usort function, that sorts array by name, but I don't know how to sort it also by platform (so that xbox would be on the last position).

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

I would like to get array sorted like this:

Array
(
[0] => Array
(
    [0] => Assassins Creed: Syndicate
    [1] => 199
    [2] => PC
    [3] => 1
)
[1] => Array
(
    [0] => Assassins Creed: Syndicate
    [1] => 199
    [2] => PC
    [3] => 1
    )
[2] => Array
(
    [0] => Assassins Creed: Syndicate
    [1] => 199
    [2] => XONE
    [3] => 1
)
)

Thank you very much for help.

Upvotes: 1

Views: 72

Answers (4)

Ninju
Ninju

Reputation: 2530

You need array_multisort

$sort = array();
foreach($YOUR_ARRAY as $k=>$v) {
    $sort[0][$k] = $v[0];
    $sort[2][$k] = $v[2];
}



array_multisort($sort['0'], SORT_DESC, $sort[2], SORT_ASC, $YOUR_ARRAY);

Upvotes: 0

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You can use usort function like as

usort($arr, function($a,$b){
    $c = strcmp($a[0],$b[0]);
    $c .= strcmp($a[2],$b[2]);
    return $c;
});

Upvotes: 2

komodosp
komodosp

Reputation: 3618

I take it you want it sorted first by title and then by platform? (Your example has all the same titles so that's not clear)

Logically, this is no different from sorting it by one long phrase containing the title and platform, so you should be able to sort it by the concatenation of them.

function sort_by_name($a, $b)   {
   if ($a == $b)
      return 0;
   return (($a[0] . $a[2]) < ($b[0] . $b[2])) ? -1 : 1;
}

Of course, this relies on the title being spelled exactly the same in each instance (incl. spaces, capitalisation etc.) but you'd have that with any sort

Upvotes: 0

Fredrik Andersson
Fredrik Andersson

Reputation: 121

Take a look at array_multisort()

In short you build two arrays from the values you want to sort by and pass them into array_multi_sort()

Upvotes: 0

Related Questions