0

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.

1
  • 2
    Where is the line which actually initiates the sorting? There must be something like usort(). Here is a correct example: eval.in/79635 Commented Dec 15, 2013 at 15:55

3 Answers 3

1

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;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.