随机链接 PHP
已编辑
我正在尝试在所有页面的底部设置一个随机链接。我正在使用下面的代码,但希望将其设置为当前页面不包含在链接的随机旋转中。
示例:
我需要代码来随机选择并显示这些链接之一。例外的是,如果当前正在查看article1.php,我希望将其从随机选择中排除。这样,在任何给定的文章中只能看到其他文章的链接。
http://mysite.com/article1.php
http://mysite.com/article2.php
http://mysite.com/article3.php
EDITED
I'm trying to setup a random link at the bottom of all my pages. I'm using the code below, but want to make it so the current page is not included in the random rotation of links.
Example:
I need code to randomly select and display ONE of these links. The exception being, IF article1.php is currently being viewed, I want it to be excluded from the random selection. That way only links to OTHER articles are seen on any given article.
http://mysite.com/article1.php
http://mysite.com/article2.php
http://mysite.com/article3.php
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用 array_rand 与类似的东西:
其中链接使构建更容易一个数组。尽管如此,我认为我们错过了一些有关如何获取链接的细节。
“当前页”是什么意思?因为最简单的方法就是不将页面添加到数组中。
并且 array_rand 的使用避免了与数组大小等的混淆。
编辑:我想你使用数据库,所以你可能有一个像这样的sql请求:
所以你知道当前文章的id。现在,您只需使用其他一些文章构建一个数组,并使用如下查询:
并使用这些结果构建候选数组。
I would use array_rand with something like:
Where links makes it easier to build an array. Nevertheless, I think we miss some details about how you grab your links.
What is the mean of "current page"? because the simplest way to do, is just not add the page to the array.
And the use of array_rand avoids confusion with size of array and so.
Edit: I suppose you use a database, so you may have an sql request like:
So you know the id of the current article. Now you just have to build an array with some other articles with a query like:
And build the candidate array with those results.
每次随机选择要显示的 URL 时,将其从数组中弹出并将其存储在临时变量中。然后,在下一次循环中进行选择,然后将之前使用的 URL 推回到数组中。
Each time you randomly choose a URL to display, pop it off of the array and store it in a temporary variable. Then, on the next rotation make your selection and THEN push the previously used URL back into the array.
确保在每个页面加载时,您不会收到之前的 URL。然而,这只是一个例子。您可能希望合并文件锁定、异常处理(也许)或完全不同的存储介质(数据库等)。
为了确保 URL 与当前 URL 不同,这应该可以解决问题:
Google“PHP get current URL” ,您将获得捕获当前 URL 的更详细方法。例如,关于是否使用HTTPS的条件,将“s”附加到协议组件。
Ensures that on each page load, you will not receive the previous URL. This, however is just an example. You would want to incorporate file locking, exception handling (perhaps) or an entirely different storage medium (DB, etc.)
To ensure the URL is not the same as the current, this should do the trick:
Google "PHP get current URL", and you'll get considerably more detailed ways to capture the current URL. For example, conditions on whether or not you're use HTTPS, to append an 's' to the protocol component.
尝试下面的代码:
try the codes below :