Randomize results with PHP

Asked

Viewed 762 times

5

I have such a structure (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 the results from 1 to 9 so that all banners when giving a refresh receive a variable with a random number and that does not repeat.

Something like: meubanner_$numeroaleatorio. I don’t know exactly what this process is related to, loop or something else.

  • 1

    Hi Marcos, I edited the question tags and I assumed that is the do_shortcode of Wordpress. That’s right?

  • Well, I searched the web and there are no other instances of the function do_shortcode(). Only if it’s a custom function of yours, and if that’s the case, adjust the tags and give me a tap to adapt my response.

  • 1

    You can use the function Rand(initial number, final number), which is native <?php echo do_shortcode("meubanner_".Rand(0,10)); ? >. And of course you save on lines of code.

7 answers

10

Another way to do not exactly 'random' is to take the banner array and call shuffle() to shuffle it. Then you can 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 that is to 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

  • It is also a solution since the amount of banners is exact and can be drawn. Thanks for the solution presented.

6

Wouldn’t that be?

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

Or better, not to repeat, use the function array_rand(). Create an array with the 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]]);
}
  • That was the answer I was looking for amid so many possible solutions. Congratulations!

6

Instead of doing 9 shortcodes [meubanner_*] in Wordpress, this can be solved with one: [meubanner]. I adapted to solution of Mary to make the random number without repetition. And I made a plugin OOP to be able to store the array of numbers already selected.

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

<?php
/**
 * Plugin Name: (SOPT) Nove shortcodes randomicos
 * Plugin URI:  /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 /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:

ss

  • And in this code you have already added to be shown three at a time as the need presented?

  • 1

    I updated the answer by incorporating the creation of Divs within the class and showing the obtained result.

5

In php is what they said.... rand(1,9) As it comes to banner, something like an image... it would not 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); 
}

5


For no repetition use this code:

Online Example: Ideone

<?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>

inserir a descrição da imagem aqui

Obs: the Function do_sortcode placed in my example is simply for testing.

  • 2

    This solution is perfect and exactly what I need because there is no need to stay inside a loop or any element that individualizes execution to a specific block of code, like you can put it anywhere.

4

Let me propose another possibility, no 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 function do_shortcode, as long as it can be located within the scope of the Application, it will do what it has to do, whatever it is.

By way of example, a simple implementation like this:

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

Within the previous code, would show something like (since it’s 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>

4

you can do this using php’s Rand() function. follows example of usage:

 int rand ( int $min , int $max )

Then just concatenate with the string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.