Sort array by a property

Asked

Viewed 633 times

8

I am trying to sort an array by a specific property(weight), I found some possible solutions but they did not work for my case, someone would know where I am doing something wrong or another way out of my need?

How I’m trying to accomplish ordination:

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 />";

}

Exit:

teste5.php - 9

teste4.php - 4

teste3.php - 8

teste2.php - 5

teste1.php - 10

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);
}
  • I will test as soon as I return to the office Rodrigo, but I believe that is the correct answer. Thank you!

1

As of PHP version 7 Spaceship Operator who assists in this task.

It replaces the conditions (or the ternary) used in the another answer:

$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
        )

)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.