PHP - 仅洗牌数组的一部分 [英] PHP - shuffle only part of an array

查看:32
本文介绍了PHP - 仅洗牌数组的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

$animals = 数组 ('长颈鹿','狮子','河马','狗','猫','兔子','飞','仓鼠','沙鼠''金鱼');

这是我希望数组除了这两个之外的顺序 - hamstergerbil

我想随机选择哪个先出现.我知道我可以使用:

shuffle($animals);

将它们全部随机化,但我只想为这两个做.所以如果我要做一个 print_r($animals) 我可能会让仓鼠在沙鼠之前出现,但另一次在沙鼠之前仓鼠

解决方案

你可以拼接数组到元素,随机排列它们的顺序并把它们放回原来的数组:

<前>$sub = array_splice($animals, 7, 2);洗牌($sub);array_splice($animals, 7,0, $sub);var_dump($animals);

I have an array as so:

$animals = array (
    'giraffe',
    'lion',
    'hippo',
    'dog',
    'cat',
    'rabbit',
    'fly',
    'hamster',
    'gerbil'
    'goldfish'
);

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆