0

How do you sort an array in numerical order, based on a numerical value within the element: where the element is a String?

for eg. from:

Array(
0 => One:3 
1 => Two:1
2 => Three:4
3 => Four:2
)

to:

Array(
    0 => Two:1
    1 => Four:2
    2 => One:3
    3 => Three:4
    )
Cœur
  • 32,421
  • 21
  • 173
  • 232

2 Answers2

1

Given your input array:

$arr = array('One:3','Two:1','Three:4','Four:2');
usort($arr, function($a, $b) {
  return filter_var($a, FILTER_SANITIZE_NUMBER_INT) - filter_var($b, FILTER_SANITIZE_NUMBER_INT);
});
print_r($arr);

outputs:

Array
(
    [0] => Two:1
    [1] => Four:2
    [2] => One:3
    [3] => Three:4
)
Joe Frambach
  • 25,568
  • 9
  • 65
  • 95
  • this one works! what about if the values were decimal? I used FILTER_VALIDATE_FLOAT instead of FILTER_SANITIZE_NUMBER_INT for the decimals but it didn't seem to work. – Miss_New_Developer May 21 '14 at 03:29
  • `filter_var($a, FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_ALLOW_FRACTION)` The third parameter is needed to allow `.` to be filtered – Joe Frambach May 21 '14 at 04:44
0

If your string follow this pattern you can use the uasort() function and build a function that sorts it. Example:

$elements = array('One:3','Two:1','Three:4','Four:2');

uasort($elements, function($a, $b){
    $a = array_pop(explode(':', $a));
    $b = array_pop(explode(':', $b));

    if ($a == $b) {
        return 0;
    }

    return ($a < $b) ? -1 : 1;
});

print_r($elements); // Array ( [1] => Two:1 [3] => Four:2 [0] => One:3 [2] => Three:4 )
lsouza
  • 2,283
  • 4
  • 24
  • 35