PHP - 洗牌数组中的一部分 [英] PHP - shuffle only part of an array
本文介绍了PHP - 洗牌数组中的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组像这样:
$animals = array (
'giraffe',
'lion',
'hippo',
'dog',
'cat',
'rabbit',
'fly',
'hamster',
'gerbil'
'goldfish'
);
这是我想要的阵列从这些2相隔的顺序 - 仓鼠
和沙鼠
That is the order i want the array to be in apart from these 2 - hamster
and gerbil
我想随机化的排在最前面它们之间。我知道我可以使用:
I would like to randomise between which one comes first. I know i can use:
shuffle($animals);
要随机化所有这些,但我想这样做只是这些2.所以,如果我是做一个的print_r($动物)
我可能会仓鼠沙鼠来之前但其他时间仓鼠之前获得沙鼠
To randomise them all but i want to do it for just these 2. So if i was to do a print_r($animals)
i may get hamster come before gerbil but another time get gerbil before hamster
推荐答案
可以拼接
的那些元素的数组,随机它们的顺序,并把它们放回原数组:
You can splice
the array for those to elements, randomize their order and put them back in the original array:
$sub = array_splice($animals, 7, 2);
shuffle($sub);
array_splice($animals, 7,0, $sub);
var_dump($animals);
这篇关于PHP - 洗牌数组中的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文