1

Whats the best/easiest way to get this:

what i have:

array('100', '100', '100', '80', '70', '70', '50', '45');

what the output should look like:

100 (random order)
100 (random order)
100 (random order)
80
70 (random order)
70 (random order)
50
45
4
  • 2
    What's the point of randomly outputting the same values? Commented Jul 18, 2012 at 9:24
  • the values also include data like a name and image and this people should be randomized by its value and DESC order if they dont have the same value Commented Jul 18, 2012 at 9:28
  • Does it matter which 70 comes first if they are the same value? Commented Jul 18, 2012 at 9:32
  • as its a ranking system and they have the same value noone of them should be favored Commented Jul 18, 2012 at 9:35

2 Answers 2

4

you have to use usort or uasort (uasort keeps keys of the array). Using PHP 5.3, you may do it like this :

shuffle($array); // randomize

uasort($array, function($a, $b){
    if($a === $b) {
        return rand(0, 1);
    }
    return $a < $b;
});

You may have to name the function before, like the php documentation shows http://www.php.net/manual/fr/function.uasort.php

Sign up to request clarification or add additional context in comments.

3 Comments

this sound good... i tried it but the output is not as i excepted: theres no random right now and the sorting is like: 100,100,45,70,70
Yeah you need a shuffle() on the array before using uasort, forgot it sorry :)
One user defined sort function is enough but you have to return -1, 0 or 1 instead of 0 or 1 for the same and a boolean for differnt!. Try this: usort($this->_ads, function ($a, $d) { if ($a == $b) { return mt_rand(0, 2) - 1; } return ($a > $b) ? -1 : 1; });
0

You can use usort (http://www.php.net/manual/en/function.usort.php) or uksort depending on your requirements. You can then choose to randomly return a positive or negative number if the values are equal.

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.