2015-02-24 44 views
0

我在网上发现了这个精彩的片段。 它在页面刷新时随机显示一个新的证明,并且想知道如何以升序而不是随机显示数组?我如何排序数组而不是随机

$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]; ?> 

澄清:

我张贴显示一个告别赛随机代码刷新页面。我希望它保持此功能,并一次只显示一个,但我希望它们按照它们添加的顺序显示。

+0

在这种情况下不要使用'rand()'? – 2015-02-24 16:21:09

回答

0

使用排序按升序

$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

我会在哪里放置这个或这个替换的东西? – Aaron 2015-02-24 16:25:41

+0

尝试这样''目标= sort($ testimonials,$ num-1);'但它没有显示刷新的新证明? – Aaron 2015-02-24 16:32:22

+0

没有。直接做这样的'sort($ testimonials);'不需要在其他变量中赋值。 – Ranjith 2015-02-24 16:36:00

0

您可以使用排序()以升序排列数组的值进行排序。这是它的文档。

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

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

$myarray = array('aa', 'bb', 'abc', 'cde', 'az'); 
sort($myarray); 
var_dump($myarray); 

此外(因为“我的代码公布显示一个告别赛随机页面的刷新我会。喜欢它来保持此功能,并一次只显示一个,但显示的评价顺序为“OP添加说明”):

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

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

感谢您的回答,我不太清楚如何使用^ PHP对我来说仍然有点神秘。 – Aaron 2015-02-25 09:47:59