【发布时间】:2014-07-14 15:40:18
【问题描述】:
我想像这样随机化一些字符串。
默认字符串:
one,two,three,four,five,six,seven
我需要:
six,three,one,seven,two,four,five
我只需要随机排列每一个的顺序,用,分隔。
如何在 PHP 中做到这一点?
【问题讨论】:
-
可以提供一些你已经尝试过的概念证明,即使你没有成功并且没有产生任何结果:)
我想像这样随机化一些字符串。
默认字符串:
one,two,three,four,five,six,seven
我需要:
six,three,one,seven,two,four,five
我只需要随机排列每一个的顺序,用,分隔。
如何在 PHP 中做到这一点?
【问题讨论】:
$input = 'one,two,three,four,five,six,seven';
$myArray = explode(',', $input);
shuffle($myArray);
echo implode(',', $myArray);
【讨论】:
// We can't shuffle a list, but we can shuffle an array.
$things = array('one','two','three','four','five','six','seven');
// Shuffle randomly changes the order of the array. It uses references so it doesn't
// make a copy of the array.
shuffle($things);
// then to display on the screen, either
foreach ($things as $thing) {
echo $thing.'<br>';
}
// or
echo implode(',', $things);
【讨论】:
创建两个数组。首先,放置有序列表。
$things = array('one','two','three','four','five','six','seven');
然后创建一个与 $things 数组元素个数相同的随机数数组。
$numItems = count($things)
for ($i = 0; $i < $numItems; $i++) {
$randomLst[$i] = $i;
$temparray[$i] = mt_rand(0, 1073741823);
}
array_multisort($temparray, SORT_ASC, $randomLst, SORT_ASC);
所以现在你有了你的项目数组和一个随机的数字数组。使用随机数字数组来调用您的项目数组。像这样。
for ($i = 0; $i < $numItems; $i++) {
echo $things[$randomLst][i];
}
当你需要一个新的随机列表时,创建一个新的 $randomLst。
【讨论】: