首页 > 解决方案 > 两个链接随机php

问题描述

我有 n 个链接,每个链接都有自己的关键字。我想一次显示两个链接,在 php.ini 中随机显示。有什么建议吗?

这是输入示例:

$text[1] = "<a href=https://www.website.ext/post-1/>words 1</a>";

$text[2] = "<a href=https://www.website.ext/post-2/>words 2</a>";

$text[3] = "<a href=https://www.website.ext/post-3/>words 3</a>";

$text[4] = "<a href=https://www.website.ext/post-4/>words 4</a>";

$text[5] = "<a href=https://www.website.ext/post-5/>words 5</a>"

....

输出示例:

words 1

words 3

or

words 5

words 2

or

words 4

words 1

标签: php

解决方案


这是您可以遵循以完成任务的代码示例。您可以使用mt_rand()函数从数组中选择一个随机索引然后回显它,或者使用array_rand()函数从数组中随机提取给定数量的元素。

<?php
#example 1
$text = array("a", "b", "c", "d", "e");

$keys = array_rand($text, 2);

echo $text[$keys[0]] . "\n";
echo $text[$keys[1]] . "\n";

#example 2

$text = array("a", "b", "c", "d", "e");

echo $text[mt_rand(0,4)] . "\n";
echo $text[mt_rand(0,4)] . "\n";

?>

推荐阅读