Pergunta

Hallo, como posso passar mais parâmetros para nós? Eu tenho funções diferentes, que são muito semelhantes em estrutura, quero ter apenas uma função:

<?php

     $arr = array(      array('number' => 100, 'string'=>'aaa'),
                array('number'=>50, 'string'=>'bdef'),
                array('number'=>150, 'string'=>'cbba')
            );


    usort($arr,  'sortNumberDesc');

    //How can I use just a single function?
    //How can I pass further parameters to usort?

    function sortNumberDesc($a, $b){
       $a = $a['number'];
       $b = $b['number'];
       if ($a == $b) return 0;
       return ($a > $b) ? -1 : +1;
    }

    function sortNumberAsc($a, $b){
       $a = $a['number'];
       $b = $b['number'];  
       if ($a == $b) return 0;
       return ($a < $b) ? -1 : +1;
    }

    //I want to do the same with just one function:
    //Sort ID is the search index, reverse DESC or ASC 
    function sort($a, $b, $sortId='number', $reverse = 0){
       $a = $a[$sortId];
       $b = $b[$sortId]; 
       if ($a == $b) return 0;
       if($reverse == false) return ($a > $b) ? -1 : +1;
       else return ($a < $b) ? -1 : +1;
    }

    print_r($arr);
?>
Foi útil?

Solução

Você pode usar uma função muito mais simples:

function sortNumberAsc($a, $ b){
       $a = $a['number'];
       $b = $ b['number'];  
       if ($a == $b) return 0;
       return ($a < $b) ? -1 : +1;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top