views:

285

answers:

2

I've got the following structue of array:

Array
        (
            [0] => Array
                (
                    [configuration_id] => 10
                    [id] => 1
                    [optionNumber] => 3
                    [optionActive] => 1
                    [lastUpdated] => 2010-03-17 15:44:12
                )

            [1] => Array
                (
                    [configuration_id] => 9
                    [id] => 1
                    [optionNumber] => 2
                    [optionActive] => 1
                    [lastUpdated] => 2010-03-17 15:44:12
                )

            [2] => Array
                (
                    [configuration_id] => 8
                    [id] => 1
                    [optionNumber] => 1
                    [optionActive] => 1
                    [lastUpdated] => 2010-03-17 15:44:12
                )
    )

What's the best way for order the array, in an incremental way based on the optionNumber?

So the results look like:

Array
        (
            [0] => Array
                (
                    [configuration_id] => 8
                    [id] => 1
                    [optionNumber] => 1
                    [optionActive] => 1
                    [lastUpdated] => 2010-03-17 15:44:12
                )

            [1] => Array
                (
                    [configuration_id] => 9
                    [id] => 1
                    [optionNumber] => 2
                    [optionActive] => 1
                    [lastUpdated] => 2010-03-17 15:44:12
                )

            [2] => Array
                (
                    [configuration_id] => 10
                    [id] => 1
                    [optionNumber] => 3
                    [optionActive] => 1
                    [lastUpdated] => 2010-03-17 15:44:12
                )
    )
+4  A: 

Use usort.

function cmp_by_optionNumber($a, $b) {
  if ($a["optionNumber"] == $b["optionNumber"]) return 0;
  if ($a["optionNumber"] > $b["optionNumber"]) return 1;
  return -1;
}

...

usort($array, "cmp_by_optionNumber");
KennyTM
That doesn't really helpe me as usort requires I provide it a function to use - which is the difficult bit I can't get my head round
Sjwdavies
Well he just gave you the function to use. And you're going to have to accept that there's not always a built-in function to do what you want, you have to write it yourself. Comparison functions just require a return of 1, 0, or -1 indicating the sort order for two elements.
Tesserex
I looked further into usort and it is actually quite cool.I wrote a simple comparison function to the one above, however missed out the '=='.Thanks for the help guys
Sjwdavies
+3  A: 

Use usort

 usort($array, 'sortByOption');
 function sortByOption($a, $b) {
   return strcmp($a['optionNumber'], $b['optionNumber']);
 }
St. John Johnson