php数组排序包含的值

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?

Thanks

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

ACCORDING TO YOUR UPDATE

try this cmp()

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

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"]);
print_r($sorted);

You loose this value

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

at each iteration i guess. Check this link for php foreach loop:

PHP FOREACH

For sorting u can use sort function of php:

PHP SORT

Your foreach will not really generate anything useful. So I created an example array to illustrate the principle:

$array = array(
    array(
        'type' => 'type a',
        'strength' => '10',
        'value' => '12',
    ),
    array(
        'type' => 'type b',
        'strength' => '12',
        'value' => '15',
    ),
    array(
        'type' => 'type c',
        'strength' => '11',
        'value' => '6',
    ),
);

Now you want this multi dimensional array to be sorted by the value, so you would have a list if it was descending order, of type b, type a and then type c.

The function you are looking for is array_multisort(). Here a sample how to use it on this particular instance. First you need to create that sorter array for the function to do it's job. Then just use multisort and you are done.

$sorter = array();

foreach ($array as $key => $row) {
    $sorter[$key] = $row['value'];
}

array_multisort($sorter, SORT_DESC, $array);

Now $array has been resorted according to the specifications. Use SORT_ASC to reverse the sorting.

Added code: Just for sake of completeness, here is your foreach code that should technically create what you wanted to in the first place:

$array = array();

foreach($cursor as $obj) {
   $row = array();

   $row['type']  = $obj['type'];
   $row['strength']  = $obj['strenght'];
   $row['value'] = rand(5, 15);

   $array[] = $row;
}

Also you have a typo in strength :)

Since you are working with integer values, you can simply use this:

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

It will sort your keys in descending order, if you want to change that to ascending, swap $a and $b.


Sorting functions generally expect the compare function to return a value of 0 if the items are the same, <0 if the first argument is less than the second (whatever less means in the particular case) and >0 if the first argument is greater than the second.

With integer values this can simply be written as $a - $b or $b - $a.