April 15, 2012

php arrays sorting contained values

Question by enrico

Ok, first of all, I’m not even sure the title is right, if so, I’m sorry.

I have this loop here which is the result of a MongoDB query:

foreach($cursor as $obj) {
   $monster = $obj["type"];
   $strenght = $obj["strenght"];
   $obj["value"] = rand(5, 15);

now, I have put rand there to signify that value changes for each iteration. Now i want that this array, when is printed, is ordered by that $obj["value"], and be able to chose if ascending or descending.

ok, I have tried this

foreach($cursor as $obj) {
   $type = $obj["monster"];
   $strenght = $obj["strenght"];
   $obj["value"] = rand(5, 15);

   $newarr[] = $obj;

    usort($newarr, "cmp");
    function cmp($a, $b)
    { return $b['value'] < $a['value']; }

    foreach ($newarr as $obj)
        echo $obj['value'] . $obj['type'] . "<br/>";

As I expected, the

 $obj["value"] = rand(5, 15);

does not get lost at every iteration in fact, the $newarr contains that value, the problem is that it does not sort them at all. The items are printed in the same order as they were put inside the array. Any help?


Answer by thecodeparadox

function mysort ($arr,$d='asc') { 
        global $dir; 
        $dir = $d; 
        uasort($arr, 'cmp'); 
        return ($arr); 
    function cmp ($a, $b) {
        global $dir;
        if($a['value'] == $b['value']) return 0;
        else  {
            if(strtolower($dir) == 'asc')
                return ($a['value'] > $b['value']) ? 1 : -1;
            else if(strtolower($dir) == 'disc')
                return ($a['value'] > $b['value']) ? -1 : 1;

    print_r(mysort($obj, 'disc'));


try this cmp()

function cmp($a, $b) {
    if($a['value'] == $b['value']) return 0;
    return $a['value'] > $b['value'] ? 1 : -1;

Answer by Starx

First of all, by doing $obj["value"] = rand(..) you are assigning same array variable with different values multiple times. By the end of the loop, the variable will only contain one value.

You probably were trying to do this

$obj["value"][] = rand(5, 15); //This adds a new random item to the array contained in $obj['value'] each time

When you have an array items, you can sort them by using sort()[ascending] function rsort()[Descending[

$sorted = sort($obj["value"]);

Please fill the form - I will response as fast as I can!