PHP - array shuffle

Asked

Viewed 402 times

0

I’m programming a page of feed on news in PHP.

I ask for your help to help me shuffle the array $tagsArray for posts not always stay in the same order.

Thank you in advance!

Code:

<?php
    $conexao = mysqli_connect("localhost","root","","newsite");

    $seguindoID= "android,Flash,iPrimePortas,";
    $tagsArray = explode(',', $seguindoID);
    $sizeSeguindo= count($tagsArray) -1;

    for($i=0; $i<=$sizeSeguindo; $i++){
        $sql = "select * from postpagina where pagina='$tagsArray[$i]'";
        $query = mysqli_query($conexao, $sql);

        while($linha = mysqli_fetch_assoc($query)){
            $userPost = $linha['pagina'];
            $post = $linha['post'];

            echo "<div><label>Postado por <b>$userPost</b> - $post</label></div>";
        }
    }
?>

2 answers

3


You can also use the function RAND of Mysql.

SELECT * FROM postpagina WHERE pagina='$tagsArray[$i]' ORDER BY RAND();

Thus the function mysqli_fetch_assoc, will already return the elements in random order.

Demonstration

  • 1

    It worked perfectly too, thank you.

1

Instead of printing directly, save each one in an array.

$itens[] = "<div><label>Postado por <b>$userPost</b> - $post</label></div>";

then use one of the functions listed here PHP: Ordering Arrays - Manual

as an example:

shuffle($itens)

and print the result using foreach for example:

foreach( $itens as $item){
    echo $item;
}

will always be printed in random order

  • 1

    It worked perfectly, thanks friend!

Browser other questions tagged

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