例如,我有以下顺序:橙,香蕉,苹果和覆盆子。我想依次显示3个数据,如下所示:
等 注意 : 我要显示的数据量发生了变化
我尝试使用array_push
和array_pop
,但在我想将其随机化时会卡住。这是我的代码:
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
array_pop($stack);
print_r($stack);
?>
任何人都可以修复我的代码吗?
答案 0 :(得分:0)
您可以使用以下代码:
function pickElementsFromArray($array, $countToPick)
{
$start = rand(0, count($array)-1);
$picked = 0;
$elements = [];
while ($picked < $countToPick) {
$elements[] = $array[$start];
$start++;
if ($start >= count($array)) {
$start = 0;
}
$picked++;
}
return $elements;
}
$array = ["orange", "banana", "apple", "raspberry"];
$elemsToPick = 3;
$elements = pickElementsFromArray($array, $elemsToPick);
此函数从随机位置开始拾取,然后从该位置拾取n个元素。如果到达数组的末尾,它将从头开始
答案 1 :(得分:0)
您可以尝试
using (var connection = factory.CreateConnection())
{
using(var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchangeName, "topic", true, false, null);
//This enables producer confirm
channel.ConfirmSelect();
var properties = channel.CreateBasicProperties();
properties.Persistent = true;
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchangeName, topic, properties, body);
channel.WaitForConfirms();
Console.WriteLine("I sent a message !", message);
}
}
输出:
橙色 香蕉 苹果
香蕉 苹果 覆盆子
苹果 覆盆子 橙色