4

I have an array with specific values in it and i would like to sort the array on a specific value in it. For instance, TOTCOM_METIER DESC. Ex :

Array
(
[0] => Array
    (
        [TOTCOM_METIER] => 1
        [metier] => Traiteur
    )

[1] => Array
    (
        [TOTCOM_METIER] => 4
        [metier] => Restauration traditionnelle
    )

[2] => Array
    (
        [TOTCOM_METIER] => 2
        [metier] => Coiffure
    )

)

I would like to sort it on TOTCOM_METIER DESC to have this result :

Array
(
[0] => Array
    (
        [TOTCOM_METIER] => 4
        [metier] => Restauration traditionnelle
    )

[1] => Array
    (
        [TOTCOM_METIER] => 2
        [metier] => Coiffure
    )

[2] => Array
    (
        [TOTCOM_METIER] => 1
        [metier] => Traiteur
    )

)
Vince
  • 109
  • 1
  • 8

4 Answers4

8
<?php

$arr = Array(
    0 => Array
        (
            'TOTCOM_METIER' => 1,
            'metier' => 'Traiteur'
        ),
    1 => Array
        (
            'TOTCOM_METIER' => 4,
            'metier' => 'Restauration traditionnelle'
        ),
    2 => Array
        (
            'TOTCOM_METIER' => 2,
            'metier' => 'Coiffure'
        )
);

//define custom "comparator" (in reverse order)
function cmp($a, $b){
    $key = 'TOTCOM_METIER';
    if($a[$key] < $b[$key]){
        return 1;
    }else if($a[$key] > $b[$key]){
        return -1;
    }
    return 0;
}
usort($arr, "cmp");

print_r($arr);

?>
ewcz
  • 12,819
  • 1
  • 25
  • 47
  • works like a charm! thks – Vince Mar 20 '17 at 12:52
  • In PHP >= 7 you might also change all ifs & returns to `return $a[$key] <=> $b[$key];` thanks to [spaceship operator](https://stackoverflow.com/questions/30365346/what-is-the-spaceship-operator-in-php-7). – Igor Bykov Aug 09 '19 at 23:49
3

Try this,

function compare($a, $b)
{
   return ($a['TOTCOM_METIER']< $b['TOTCOM_METIER']);
}
usort($your_array, "compare");

Here is usort docs which states Sort an array by values using a user-defined comparison function

Rahul
  • 18,271
  • 7
  • 41
  • 60
0

How do you get this data ? If you select from db system,you can use order by TOTCOM_METIER desc in your select sql.

Delly.Liu
  • 1
  • 4
0

With this you can pass the order you want, "desc" or "asc"

function sortAsc($a, $b) {
   return ($a[TOTCOM_METIER] < $b[TOTCOM_METIER]);
}

function sortDesc($a, $b) {
   return ($a[TOTCOM_METIER] > $b[TOTCOM_METIER]);
}

function sortMyArray($array, $order = "asc") {
    if($order === "desc") {
        return usort($array, "sortDesc");
    }

    return usort($array, "sortAsc");
}

// Call it like
sortMyArray($array, "asc");
napolux
  • 15,574
  • 9
  • 51
  • 70