Randomize results with PHP

5

I have a structure like this (which I created):

<div class="banners">
     <?php echo do_shortcode("meubanner_1")?>
     <?php echo do_shortcode("meubanner_2")?>
     <?php echo do_shortcode("meubanner_3")?>
</div>
<div class="banners">
     <?php echo do_shortcode("meubanner_4")?>
     <?php echo do_shortcode("meubanner_5")?>
     <?php echo do_shortcode("meubanner_6")?>
</div>
<div class="banners">
     <?php echo do_shortcode("meubanner_7")?>
     <?php echo do_shortcode("meubanner_8")?>
     <?php echo do_shortcode("meubanner_9")?>
</div>

I need to randomize results from 1 to 9 so that all banners on refresh receive a variable with a random number that does not repeat itself.

Something like: meubanner_$numeroaleatorio . I'm not sure exactly what this process is, loop, or anything else.

    
asked by anonymous 02.09.2014 / 15:18

7 answers

5

To avoid repetition use this code:

Idea Ideone p>

<?php
    $array_number = array();
    for($i = 1; $i <=9; $i++)
    {
        $value = rand(1,9);
        while (in_array($value, $array_number))
        {
            $value = rand(1,9);
        }
        $array_number[$i - 1] = $value;
    }
    function do_shortcode($value){
        return $value;
    }
?>

<div class="banners">
     <?php echo do_shortcode("meubanner_".$array_number[0]);?>
     <?php echo do_shortcode("meubanner_".$array_number[1]);?>
     <?php echo do_shortcode("meubanner_".$array_number[2]);?>
</div>
<div class="banners">
     <?php echo do_shortcode("meubanner_".$array_number[3]);?>
     <?php echo do_shortcode("meubanner_".$array_number[4]);?>
     <?php echo do_shortcode("meubanner_".$array_number[5]);?>
</div>
<div class="banners">
     <?php echo do_shortcode("meubanner_".$array_number[6]);?>
     <?php echo do_shortcode("meubanner_".$array_number[7]);?>
     <?php echo do_shortcode("meubanner_".$array_number[8]);?>
</div>

    
02.09.2014 / 15:34
10

Another way to do not exactly 'random' is to get the array of banners and call shuffle () to shuffle it. You can then create a function that removes items from the array to avoid repetition using array_shift () . The & symbol means that the variable is passed as reference or at each function call an item will be removed from $banners

function exibirBanner(&$arr){
   if(!empty($arr)) return array_shift($arr);
}

$banners = array('banner1', 'banner2', 'banner3', 'banner4');
shuffle($banners);


echo exibirBanner($banners) .'<br>';
echo exibirBanner($banners) .'<br>';
echo exibirBanner($banners) .'<br>';
echo exibirBanner($banners) .'<br>';
echo exibirBanner($banners) .'<br>';
echo exibirBanner($banners) .'<br>';

Example

    
02.09.2014 / 15:52
6

Would not that be?

<?php echo do_shortcode("meubanner_".rand(1,9))?>

Or rather, not to repeat, use the array_rand() function. Create a vector with numbers 1-9 and randomize, then with a loop create the structure you want.

$vetor = array('1', '2', '3', '4', '5', '6', '7', '8', '9');
$random = array_rand($vetor, 9);

for ($i=0; $i<9; $i++) {
   echo do_shortcode("meubanner_".$vetor[$random[$i]]);
}
    
02.09.2014 / 15:23
6

Instead of making 9 shortcodes [meubanner_*] in WordPress, this can be solved with only one: [meubanner] . I've adapted the Maria solution to make the random number without repetition. And I made a plugin OOP to store the array of numbers already selected.

Each time the do_shortcode("[meubanner]") is called, the Shortcode will execute the random() method that returns a random number that is not in the $num_selecionados array. Before returning, the new number is stored in the array avoiding its repetition.

<?php
/**
 * Plugin Name: (SOPT) Nove shortcodes randomicos
 * Plugin URI:  https://pt.stackoverflow.com/a/31205/201
 * Author:      brasofilo 
*/

add_action(
    'plugins_loaded',
    array ( SOPT_31161_Shortcode::get_instance(), 'plugin_setup' )
);

class SOPT_31161_Shortcode
{
    protected static $instance = NULL;
    public $num_selecionados = array();

    /**
     * Constructor. Deixado publico e vazio intencionalmente.
     */
    public function __construct() {}

    /**
     * Acessar a instancia de trabalho deste plugin.
     * @return  object of this class
     */
    public static function get_instance()
    {
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    /**
     * Usado para iniciar os trabalhos normais do plugin.
     */
    public function plugin_setup()
    {
        add_shortcode( 'meubanner', array( $this, 'shortcode' ) );
    }

    /**
     * Shortcode [meubanner]
     */
    public function shortcode( $atts, $content )
    {
        $html = sprintf(
            '<h3>Banner #%s</h3>',
            $this->random()
        );
        return $html;
    }

    /**
     * Retorna um número randomico de 1 a 9 que não esteja na array $num_selecionados
     * Inspirado em https://pt.stackoverflow.com/a/31170/201
     */
    public function random()
    {
        $value = rand( 1, 9 );

        // Executar até achar um número que não esteja em $num_selecionados
        while( in_array( $value, $this->num_selecionados ) )
            $value = rand( 1, 9 );

        // Adicionar novo número a array
        $this->num_selecionados[] = $value;

        return $value;
    }

    /**
     * Imprimir 3 divs contendo 3 shortcodes cada
     * Modo de uso: <?php SOPT_31161_Shortcode::get_instance()->print_banners(); ?>
     */
    public function print_banners()
    {
        for( $i = 1; $i <=3; $i++ )
        {
            echo '<div class="banners">';
            for( $j = 1; $j <=3; $j++ )
                echo do_shortcode( "[meubanner]");
            echo '</div>';
        }
    }
}

And in the template or widget, call the function that prints 3 divs containing 3 shortcodes each with:

<?php 
    if( class_exists( 'SOPT_31161_Shortcode' ) {
        SOPT_31161_Shortcode::get_instance()->print_banners();
    }
?>

The result is:

  

    
02.09.2014 / 17:53
5

In php is what they said .... rand(1,9) As it comes to banner, something like an image ... would not it be better to bring by js?

var numero = Array();

//Populando o array de 0 a 8
for (i=0; i < 9; i++) { 
    numero[i] = i;
}

//Sorteando
numero.sort(randOrd);

//Somente escreve o resultado, adaptável pra sua necessidade
for (i=0; i < 9; i++) { 
    document.write('<br>'+numero[i]); 
}

//Faz manipulação algébrica pra puxar o próximo resultado
function randOrd() { 
    return (Math.round(Math.random())-0.5); 
}
    
02.09.2014 / 15:30
4

You can do this using php's Rand () function. follows usage example:

 int rand ( int $min , int $max )

Then just concatenate with the string.

    
02.09.2014 / 15:26
4

Let me propose another possibility, without manual loops:

$ids = range( 1, 9 ); // Define o intervalo

shuffle( $ids ); // Embaralha

$ids = array_chunk( $ids, 3 ); // Divide em blocos de 3

// Monta a estrutura

array_walk(

    $ids,

    function( $ids ) {

        echo "<div class=\"banners\">\n\n    ";

        array_map( 'do_shortcode', $ids );

        echo "\n</div>\n\n";

    }
);

And the do_shortcode function, as long as it can be located within the scope of the Application, will do what you have to do, whatever.

By way of example, a simple implementation like this:

function do_shortcode( $id ) { printf( "meubanner_%d\n    ", $id ); }

Inside the previous code , it would show something like (since it is random):

<div class="banners">

    meubanner_3
    meubanner_9
    meubanner_2

</div>

<div class="banners">

    meubanner_1
    meubanner_8
    meubanner_6

</div>

<div class="banners">

    meubanner_7
    meubanner_4
    meubanner_5

</div>
    
03.09.2014 / 19:39