Is it correct to randomize an array in PHP?

I have an array where close values ​​are close to each other. How:

1: Apple 2: Big Apple 3: Small Apple 4: Green Apple 5: Orange 6: Small Orange 7: Ripe Orange

      

and etc.

If I call shuffle on it, the location may change to:

1: Apple  3: Small Apple 5: Orange 4: Green Apple  6: Small Orange 2: Big Apple 7: Ripe Orange

      

As you can see, most of the apples are still together. It gets worse when there are 10 items of this type. Is there a way to correctly randomize the location of each value? How about calling shuffle multiple times. Is there any other better way?

+3


source to share


2 answers


Suppose the program is designed to study the view from the last word in each element, this is the solution. (If not, just change the logic in the function kind_of()

)



<?php

// learn what kind if item is it
function kind_of($item) {
  $words = explode(' ', $item);
  return array_pop($words);
}

// reorganize as 2-dimensional array
function by_kind($input) {
  $output = array();
  foreach ($input as $item) {
    $output[kind_of($item)][] = $item;
  }
  return $output;
}


$input = array(
  'Orange',
  'Apple',
  'Big Apple',
  'Small Orange',
  'Small Apple',
  'Ripe Orange',
  'Green Apple',
);

// arrange the items in 2-dimensional by_kind array
// then shuffle each second level arrays
$by_kind = by_kind($input);
ksort($by_kind); // sort by key (kind name)
$shuffled_by_kind = array_map(function ($kind_items) {
  shuffle($kind_items);
  return $kind_items;
}, $by_kind);

// merge the second level arrays back to 1 array
$result = call_user_func_array('array_merge', array_values($shuffled_by_kind));

// see output
var_dump($result);

      

0


source


This is a working example of what you need:



public function shuffle_assoc(&$array) {
    $keys = array_keys($array);

    shuffle($keys);

    foreach($keys as $key) {
        $new[$key] = $array[$key];
    }

    $array = $new;

    return true;
}

$fruits = array(
    1 => 'Apple ',
    2 => 'Big Apple ',
    3 => 'Small Apple ',
    4 => 'Green Apple ',
    5 => 'Orange ',
    6 => 'Small Orange ',
    7 => 'Ripe Orange',
);
shuffle_assoc($fruits);
echo "<pre>"; var_dump($fruits); die;

      

0


source







All Articles