webmasters
webmasters

Reputation: 5831

Randomize the data in a multidimensional array (second tier)

I have a multidimensional array like this one:

Array
(
    [site1] => Array
        (
            [0] => Array
                (
                    [0] => data
                    [1] => data
                    [2] => data
                    [3] => data
                )

            [1] => Array
                (
                    [0] => data
                    [1] => data
                    [2] => data
                    [3] => data

                )

            [2] => Array
                (
                    [0] => data
                    [1] => data
                    [2] => data
                    [3] => data

                )

    [site2] => Array
        (
            [0] => Array
                (
                    [0] => data
                    [1] => data
                    [2] => data
                    [3] => data
                )

            [1] => Array
                (
                    [0] => data
                    [1] => data
                    [2] => data
                    [3] => data
                )

            [2] => Array
                (
                    [0] => data
                    [1] => data
                    [2] => data
                    [3] => data
                )
         )
)

I am trying to randomize the data for each site ([site1], [site2]) but don't mix the data between sites. So it would be like a second tire randomization.

For example, after the randomization, the position [0] for [site1] would have different data, maybe the data from the earlier position [3].

Any ideas how to do it?

Upvotes: 0

Views: 126

Answers (3)

hakre
hakre

Reputation: 197692

You map the shuffle function to the array:

$shuffle = function($array) {
    $r = shuffle($array);
    return $array;
};

$sites = array_map($shuffle, $sites);

Or:

foreach ($sites as &$site) shuffle($site);
unset($site);

Upvotes: 3

AlexP
AlexP

Reputation: 9857

Another, (not as good as shuffle) way ;-)

foreach ($site as $key => $data) {
  $values = array();
  $rand   = array_rand($data, count($data));
  for ($i = 0; $i < count($rand); $i++)) {
    $values[] = $site[$key][$rand[$i]];  
  }
  $site[$key] = $values;
}

Upvotes: 0

clentfort
clentfort

Reputation: 2504

foreach($sites as $i => $site) {
   shuffle($sites[$i]);
}

Upvotes: 1

Related Questions