首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何排序上升数组而不是随机数组?

如何排序上升数组而不是随机数组?
EN

Stack Overflow用户
提问于 2015-02-24 16:16:55
回答 2查看 115关注 0票数 0

我在网上找到了这个很棒的片段。它在刷新页面时随机显示了一个新的证明,我想知道如何以升序而不是随机的方式显示数组?

代码语言:javascript
复制
$target = sort(0, $num-1); 

这是我的尝试

代码语言:javascript
复制
<?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.
    */
    ?>

在页面中输出证词,内容如下:

代码语言:javascript
复制
<?php echo $testimonials[$target]; ?>

澄清:

我发布的代码在刷新页面时随机显示一个证词。我希望它保留这个函数,一次只显示一个,但我希望它们按照添加的顺序显示。

EN

回答 2

Stack Overflow用户

发布于 2015-02-24 16:22:11

使用升序排序

代码语言:javascript
复制
$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);
票数 0
EN

Stack Overflow用户

发布于 2015-02-24 16:24:54

可以使用sort()按升序排序数组的值。这是它的文档。

http://php.net/manual/en/function.sort.php

基本上,您可以这样使用它:

代码语言:javascript
复制
$myarray = array('aa', 'bb', 'abc', 'cde', 'az');
sort($myarray);
var_dump($myarray);

此外,还有(因为“我发布的代码在刷新页面时随机显示一个证明。我希望它保留此函数,一次只显示一个,但显示按顺序上升的推荐信”):

如果您希望每个页面加载只显示一个证明,那么您需要在每个页面加载上保留最后一个数组索引。如果只是每次刷新页面,那么您可以使用会话变量。就像这样:

代码语言:javascript
复制
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变量更新为下一个索引。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28700848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档