1

我怎么能排除多维数组中的某个元素,我使用 Shuffle 函数将它们随机化?

假设我有这个脚本:

$array = array(
  array("Bird", "Brown", "Bear", "Bangkok", "Bat"),
  array("Carrot", "Cat", "Crispy", "Cross", "Cable"),
  array("All", "Apple", "Adam", "Apart", "Air")
);

array_walk($array, function (&$array) { shuffle($array); });
shuffle($array);

该脚本会给我一个垂直打乱的数组和每个数组中的打乱元素。

我需要的是除了每个数组的第一个元素(位置 0)之外,请问我该怎么做?

4

1 回答 1

4

显而易见的解决方案是这样的:

// Remove and store the first element in a temporary variable
$firstElement = array_shift($array);

// Shuffle the remaining items
shuffle($array);

// Re-add (prepend) the original first item
array_unshift($array, $firstElement);

这可以很容易地应用于您的具体示例:

function customShuffle(array &$array) {
    $firstElement = array_shift($array);
    shuffle($array);
    array_unshift($array, $firstElement);
}

$array = array(
  array("Bird", "Brown", "Bear", "Bangkok", "Bat"),
  array("Carrot", "Cat", "Crispy", "Cross", "Cable"),
  array("All", "Apple", "Adam", "Apart", "Air")
);

                                         // vvvvv //
array_walk($array, function (&$array) { customShuffle($array); });
shuffle($array);  // use "customShuffle" as well if needed
于 2013-05-24T22:37:24.690 回答