随机排列除前三个元素外的数组
Shuffle array except for the first three elements
我在 PHP 中有一个数组:
Array (
[0] => Red
[1] => Green
[2] => Blue
[3] => Yellow
[4] => Purple
[5] => Orange
[6] => Brown )
除了前三个元素([0][1][2] 应保持在同一位置)之外,我希望此数组被打乱顺序。例如:
Array (
[0] => Red
[1] => Green
[2] => Blue
[3] => Brown
[4] => Yellow
[5] => Purple
[6] => Orange )
我知道如何用 shuffle( $array );
打乱整个数组,但我需要建议如何不打乱该数组的前三个元素。谢谢!
这是你可以做的:
$a=array("red","green","blue","yellow","brown");
$partA = array_slice($a,0,3);
$partB = array_slice($a,3,sizeof($a));
shuffle($partB);
$result = array_merge($partA, $partB);
print_r($result);
我在 PHP 中有一个数组:
Array (
[0] => Red
[1] => Green
[2] => Blue
[3] => Yellow
[4] => Purple
[5] => Orange
[6] => Brown )
除了前三个元素([0][1][2] 应保持在同一位置)之外,我希望此数组被打乱顺序。例如:
Array (
[0] => Red
[1] => Green
[2] => Blue
[3] => Brown
[4] => Yellow
[5] => Purple
[6] => Orange )
我知道如何用 shuffle( $array );
打乱整个数组,但我需要建议如何不打乱该数组的前三个元素。谢谢!
这是你可以做的:
$a=array("red","green","blue","yellow","brown");
$partA = array_slice($a,0,3);
$partB = array_slice($a,3,sizeof($a));
shuffle($partB);
$result = array_merge($partA, $partB);
print_r($result);