Leon Helmsley
Leon Helmsley

Reputation: 595

Sorting array numerically based on EYE_SIZE inside array's arrays

I have an array of arrays like this:

array(18) {
  [0]=>
  array(3) {
    ["ID"]=>
    string(5) "23"
    ["EYE_SIZE"]=> "203.C"
  }
  [1]=>
  array(2) {
    ["ID"]=>
    string(5) "1"
    ["EYE_SIZE"]=> "231.2A"
  }
  [2]=>
  array(2) {
    ["ID"]=>
    string(5) "32"
    ["EYE_SIZE"]=> "231.2B"
  }
  [3]=>
  array(3) {
    ["ID"]=>
    string(5) "90"
    ["EYE_SIZE"]=> "201A"
  }
  ... and so on
}

And I want the arrays in the array to be sorted alphanumerically based on the EYE_SIZE value. For example, if the array had an EYE_SIZE value of 201A, I would want it to be before arrays with EYE_SIZEs of 203A, 201B, or 201.2A.

Is there a function in PHP that can help me achieve this?

Upvotes: 0

Views: 28

Answers (1)

tim
tim

Reputation: 3359

You could use usort and write your own comparison function.

function cmp($a, $b)
{
    return strcmp($a["EYE_SIZE"], $b["EYE_SIZE"]);
}

usort($your_array, "cmp");

or with a closure

usort($your_array, function($a, $b){
    return strcmp($a["EYE_SIZE"], $b["EYE_SIZE"]);
});

Upvotes: 1

Related Questions