Order array for a property

8

I'm trying to sort an array by a specific property (weight), I found some possible solutions but they did not work for me, could anyone tell me where I'm doing something wrong or another way out of my need?

How am I trying to sort:

function ordenaPorPeso($a, $b) { 
    if($a->peso == $b->peso){ return 0 ; }
    return ($a->peso < $b->peso) ? -1 : 1;
} 

$arrayPaginas = array(  
            array("url" => "teste1.php", "peso" => 10),
            array("url" => "teste2.php", "peso" => 5),                      
            array("url" => "teste3.php", "peso" => 8),
            array("url" => "teste4.php", "peso" => 4),
            array("url" => "teste5.php", "peso" => 9)                     
            );

usort($arrayPaginas, 'ordenaPorPeso');

foreach($arrayPaginas as $pagina){

    echo $pagina["url"]. " - " . $pagina["peso"] . "<br /><br />";

}

Output:

teste5.php - 9

teste4.php - 4

teste3.php - 8

teste2.php - 5

teste1.php - 10
    
asked by anonymous 19.03.2014 / 15:52

2 answers

5

The error is in the function. Each element of $arrayPaginas is an array, not an object.

Make the following correction:

function ordenaPorPeso($a, $b) { 
    if ($a['peso'] == $b['peso']) {
        return 0;
    }
    if ($a['peso'] < $b['peso']) {
        return -1;
    }
    return 1;
}

Or, in a more concise version:

function ordenaPorPeso($a, $b) { 
    return (($a['peso'] != $b['peso']) ? (($a['peso'] < $b['peso']) ? -1 : 1) : 0);
}
    
19.03.2014 / 16:08
1

As of PHP version 7 there is the spaceship operator that assists with this task.

It replaces the conditions (or the ternary) used in the other response :

$arrayPaginas = [  
    ["url" => "teste1.php", "peso" => 10],
    ["url" => "teste2.php", "peso" => 5],                      
    ["url" => "teste3.php", "peso" => 8],
    ["url" => "teste4.php", "peso" => 4],
    ["url" => "teste5.php", "peso" => 9]                     
];

usort($arrayPaginas, function ($a, $b) {
    return $a['peso'] <=> $b['peso'];
});

print_r($arrayPaginas);

The result will be, as expected:

Array
(
    [0] => Array
        (
            [url] => teste4.php
            [peso] => 4
        )

    [1] => Array
        (
            [url] => teste2.php
            [peso] => 5
        )

    [2] => Array
        (
            [url] => teste3.php
            [peso] => 8
        )

    [3] => Array
        (
            [url] => teste5.php
            [peso] => 9
        )

    [4] => Array
        (
            [url] => teste1.php
            [peso] => 10
        )

)
    
20.11.2018 / 17:01