Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort array on specific value with php [duplicate]

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
    )

)
like image 330
Vince Avatar asked Dec 24 '22 19:12

Vince


2 Answers

<?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);

?>
like image 57
ewcz Avatar answered Dec 26 '22 09:12

ewcz


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

like image 37
Rahul Avatar answered Dec 26 '22 09:12

Rahul