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
ggzone
  • 3,661
  • 8
  • 36
  • 59

3 Answers3

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

Baptiste Placé
  • 386
  • 2
  • 5
  • 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 – ggzone Jul 18 '12 at 11:53
  • Yeah you need a shuffle() on the array before using uasort, forgot it sorry :) – Baptiste Placé Jul 18 '12 at 16:51
  • 2
    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; });``` – mabe.berlin Feb 01 '13 at 13:58
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.

Luke Mills
  • 1,616
  • 1
  • 11
  • 18
0

Try something like this: http://codepad.org/SzSeUM4u

Based on the aasort from: Sort Multi-dimensional Array by Value

Community
  • 1
  • 1
Kao
  • 2,242
  • 3
  • 22
  • 31