除了前三个元素之外的随机数组

时间:2015-02-02 11:33:37

标签: php arrays shuffle

我在PHP中有一个数组:

Array (
    [0] => Red
    [1] => Green
    [2] => Blue
    [3] => Yellow       
    [4] => Purple
    [5] => Orange
    [6] => Brown )

我希望这个数组被洗牌,除了前三个元素([0] [1] [2]应该保持在同一个位置)。 E.g:

Array (
    [0] => Red
    [1] => Green
    [2] => Blue
    [3] => Brown        
    [4] => Yellow
    [5] => Purple
    [6] => Orange )

我知道如何使用shuffle( $array );对整个数组进行随机播放,但我需要建议如何不对该数组的前三个元素进行随机播放。谢谢!

1 个答案:

答案 0 :(得分:0)

你可以这样做:

$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);