-1

I have an interesting challenge. I have an array that looks like this:

array(
 [1] = array(
   'fruit' => 'Banana'
 ),
 [2] = array(
   'fruit' => 'Apple'
 ),
 [3] = array(
   'fruit' => 'Grapes'
 )
)

I need to sort the array according to fruit, presuming the fruit have this priority:

#1: Apple

#2: Banana

#3: Grapes

Ultimately the output should be:

array(
 [2] = array(
   'fruit' => 'Apple'
 ),
 [1] = array(
   'fruit' => 'Banana'
 ),
 [3] = array(
   'fruit' => 'Grapes'
 )
)

Would this be done by some sort of usort() trickery?

Anthony
  • 4,965
  • 9
  • 45
  • 78
  • Yes, it _would_ be done with `usort()`. Does that answer your question? – Wrikken Oct 21 '13 at 20:50
  • If you can move the values to the 1st level it might be easier with array_intersect, then merge with difference – nice ass Oct 21 '13 at 20:52
  • The main thing that is throwing me off is the nested-ness. There are a bunch of other attributes in each node. Have been trying different things with usort but it's not coming out correctly yet. – Anthony Oct 21 '13 at 20:59
  • Did you try array_multisort()? Kinda what it's for. – AbraCadaver Oct 21 '13 at 21:12

2 Answers2

0

If you don't need to keep the index association:

foreach($array as $key => $values) {
    $fruit[$key] = $values['fruit'];
}
array_multisort($fruit, SORT_ASC, $array);
AbraCadaver
  • 73,820
  • 7
  • 55
  • 81
0

Example using usort:

<?php

$arr = array(
    array(
        'fruit' => 'Banana'
    ),
    array(
      ' fruit' => 'Apple'
    ),
    array(
        'fruit' => 'Grapes'
    )
);

function sortByFruit($arr1, $arr2)
{
    if ($arr1['fruit'] == $arr2['fruit']) {
        return 0;
    } elseif ($arr1['fruit'] < $arr2['fruit']) {
        return -1;
    } else {
        return 1;
    }
}

usort($arr, 'sortByFruit');
Jeroen
  • 916
  • 1
  • 6
  • 13