user3057706
user3057706

Reputation: 73

PHP Sort by Specific Field in Array

I have an array of the following structure:

Array ( [0] => Array ( [event] => event1 [Weight] => 2 )

And I am trying to sort by 'Weight'. I have tried this:

function cmp($a, $b) {
    if ($a['Weight'] > $b['Weight'] ){
        return -1;
    } else {
        return 1;
    }
}

But it isnt sorting by weight. It seems to be how i refer to weight but I am unsure how to do this correctly.

Upvotes: 0

Views: 94

Answers (3)

robbmj
robbmj

Reputation: 16526

I think your problem must be the function you use to do the actual sorting, Here is a complete example of how to sort in ether ascending or descending order.

$array = array(
        array( 'event'=> 'something', 'Weight' => 2),
        array( 'event'=> 'something', 'Weight' => 1),
        array( 'event'=> 'something', 'Weight' => 10),
        array( 'event'=> 'something', 'Weight' => 10),
        array( 'event'=> 'something', 'Weight' => 0),
        array( 'event'=> 'something', 'Weight' => 1),
        array( 'event'=> 'something', 'Weight' => -10), 
    );

function weightCmp($isAscending = true) {
    return function($a, $b) use ($isAscending) {
        $diff = $a['Weight'] - $b['Weight'];
        return $isAscending ? $diff : $diff * -1;
    };
 }

usort($array, weightCmp());
var_dump($array);

usort($array, weightCmp(false));
var_dump($array);

Upvotes: 0

undefined_variable
undefined_variable

Reputation: 6228

<?php
// Obtain a list of columns
//$data = Your Array
foreach ($data as $key => $row) {
    $weight[$key]  = $row['Weight'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($weight, SORT_ASC, $data);
?>

Upvotes: 0

scrblnrd3
scrblnrd3

Reputation: 7426

You can sort it like this:

uasort($array, function ($a, $b) {
    $c = $a['Weight'];
    $d = $b['Weight'];
    if ($c == $d){
        return 0;
    }
    else if($c > $d){
       return 1;
    }
    else{
       return -1;
    }
});

Upvotes: 1

Related Questions