-3

I need to rendomise the order of follow array using PHP, i tried to use array shuffle and array_random but no luck, can anyone help me please

Array (
  [0] => Array (
    [value] => 4
    [label] => GasGas
  )
  [1] => Array (
    [value] => 3
    [label] => Airoh Helmets
  )
  [2] => Array (
    [value] => 12
    [label] => XCiting Trials Wear
  )
  [3] => Array (
    [value] => 11
    [label] => Hebo Trials
  )
  [4] => Array (
    [value] => 10
    [label] => Jitsie Products
  )
  [5] => Array (
    [value] => 9
    [label] => Diadora Boots
  )
  [6] => Array (
    [value] => 8
    [label] => S3 Performance
  )
  [7] => Array (
    [value] => 7
    [label] => Scorpa
  )
  [8] => Array (
    [value] => 6
    [label] => Inspired
  )
  [9] => Array (
    [value] => 5
    [label] => Oset
  )
) 
3
  • how are you trying to shuffle? The shuffle function does randomize the order of elements in an array. Commented Jul 9, 2012 at 9:08
  • 1
    Take a look at stackoverflow.com/questions/4102777/… which gives you exactly the answer you want. Commented Jul 9, 2012 at 9:10
  • 1
    I just tested this an it worked for me in codepad: codepad.org/6MmaY81i Commented Jul 9, 2012 at 9:11

2 Answers 2

4
$array = array(1,2,3,4,5,6,7);
shuffle($array);
print_r($array);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks i got this wrong way before, i shuffle the array and assigned it in to a variable. :)
2

You can get a random sequence of array index, i think it will allow you to resolve your problem;)


// return random nonrecurring array of numbers
//params:
//$fromto - if $to is null, interval will be [0, $fromto], elsewhere [$fromto, $to]
//$to - end of interval.
//$limit - limit number. notice! if $limit < size([$fromto, $to]) not all numbers from interval [$fromto, $to] will be return
function rand_seq($fromto, $to = null, $limit = null){

if(is_null($to)){
$to = $fromto;
$fromto = 0; }

if(is_null($limit)){
$limit = $to-$fromto+1;

}
$randArr = array();

for($i=$fromto; $i<=$to; $i++){
$randArr[]=$i;

}
$result = array();

for($i=0; $i < $limit||sizeof($randArr) > 0; $i++){
$index = mt_rand(0, sizeof($randArr)-1); // select rand index / выбираем случайный индекс массива
$result[] = $randArr[$index]; // add random element / добавляем случайный элемент массива
array_splice($randArr, $index, 1); // remove it=) / удаляем его =)

}

return $result;
}

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.