我在网上找到了这个很棒的片段。它在刷新页面时随机显示了一个新的证明,我想知道如何以升序而不是随机的方式显示数组?
$target = sort(0, $num-1); 这是我的尝试
<?php
/*
--------------------------------------------
Random Testimonial Generator Created by:
Ryan McCormick
Ntech Communications
Website: http://www.ntechcomm.com/
Blog: http://www.ntechcomm.com/blog/
Twitter: @ntechcomm
--------------------------------------------
*/
//Start Array
$testimonials = array();
$testimonials[0] = "Testimonial 1";
$testimonials[1] = "Testimonial 2";
$testimonials[2] = "Testimonial 3";
$testimonials[3] = "Testimonial 4";
//Automate script by counting all testimonials
$num = count($testimonials);
//randomize target testimonial
$target = rand(0, $num-1);
/*
To display testimonials on site
--------------------------------------------
place the following code in the
display area:
<?php echo $testimonials[$target]; ?>
--------------------------------------------
Use a PHP include to use this code on your
target page.
*/
?>在页面中输出证词,内容如下:
<?php echo $testimonials[$target]; ?>澄清:
我发布的代码在刷新页面时随机显示一个证词。我希望它保留这个函数,一次只显示一个,但我希望它们按照添加的顺序显示。
发布于 2015-02-24 16:22:11
使用升序排序
$testimonials = array();
$testimonials[0] = "Testimonial 1";
$testimonials[1] = "Testimonial 2";
$testimonials[2] = "Testimonial 3";
$testimonials[3] = "Testimonial 4";
$random = rand(0, count($testimonials) - 1);
$asc_arr = sort($testimonials);
print_r($result);发布于 2015-02-24 16:24:54
可以使用sort()按升序排序数组的值。这是它的文档。
http://php.net/manual/en/function.sort.php
基本上,您可以这样使用它:
$myarray = array('aa', 'bb', 'abc', 'cde', 'az');
sort($myarray);
var_dump($myarray);此外,还有(因为“我发布的代码在刷新页面时随机显示一个证明。我希望它保留此函数,一次只显示一个,但显示按顺序上升的推荐信”):
如果您希望每个页面加载只显示一个证明,那么您需要在每个页面加载上保留最后一个数组索引。如果只是每次刷新页面,那么您可以使用会话变量。就像这样:
session_start();
if (!isset($_SESSION['cur_index'])) { $_SESSION['cur_index'] = 0; }
$target = $_SESSION['cur_index'];
// Prepare for the next index when the page is refreshed.
$_SESSION['cur_index']++;
// If the index goes pass the array's limit, then go back to index 0.
if ($_SESSION['cur_index'] >= count($testimonials)) {
$_SESSION['cur_index'] = 0;
}这将根据上一个索引将$target变量更新为下一个索引。
https://stackoverflow.com/questions/28700848
复制相似问题