Generate random number for an array

Asked

Viewed 1,019 times

4

I have a foreach that fetches data from a table and makes a insert in another table. I need to count the amount of foreach, and then generate a random sequence, and feed a field of insert.

Look at the code:

$dados2 = connection::select('SELECT * FROM tab1');
foreach ($dados2 as $reg) {   
    $campo1 = $reg['campo1'];
    $campo2 = $reg['campo2'];    
    $sequencia_aleatoria = '';                     
}
connection::exec("insert into tab2(campo1,campo2,sequencia_aleatoria) values('$campo1','$campo2','$sequencia_aleatoria')");

I hope you have understood my doubt.

  • From what I understand you want to fill an Array with numbers from 0 to 100 in random order ? Records cannot be entered in order and you shuffle the output ?

  • Exact @Ucas. Type beyond the autoincremet of Insert, I want to have another field, so I can change this sequence when you want.

  • But it has to be random.

  • it has to contain all the numbers from 0 to the right total number of records ? So it’s not random, it has a defined sequence but it’s assorted. You can popular an array from 0 to 100 for example, and then do a Sort

  • The second example @stderr does just that, I think it’s right

2 answers

3

uses the function uniqueid PHP, serial something like:

$dados2 = connection::select('SELECT * FROM tab1');
$contagem=0;

foreach ($dados2 as $reg) {   
    $campo1 = $reg['campo1'];
    $campo2 = $reg['campo2'];    
    $contagem++;                  
}

$sequencia_aleatoria=rand(0,$contagem);
connection::exec("insert into tab2(campo1,campo2,sequencia_aleatoria) values('$campo1','$campo2','$sequencia_aleatoria')");

the function uniqid() generates a hash based on milliseconds so there is no possibility of repetition.

I guess your code would be like this:

$dados2 = connection::select('SELECT * FROM tab1');
$numero=count(dados2);

foreach ($dados2 as $reg) {   
    $campo1 = $reg['campo1'];
    $campo2 = $reg['campo2'];    
    $sequencia_aleatoria=rand(0,$numero);

    connection::exec("insert into tab2(campo1,campo2,sequencia_aleatoria) values('$campo1','$campo2','$sequencia_aleatoria')");   
    unset($sequencia_aleatoria);    
}

Rotate this q works

<?php
$contagem=420; // aqui iioria o count($resultado);
for($i=0;$i<=$contagem;$i++){
    echo rand(0,$contagem)."<br>";
}
?>

logica he the same and ta rolando.

forehead online here http://phptester.net/

instead of you do a foreach do a for

$dados2 = connection::select('SELECT * FROM tab1');
$numero=count(dados2);

for($i=0;$i<$numero;i++) { 
    $reg=$dados2[$i];  
    $campo1 = $reg['campo1'];
    $campo2 = $reg['campo2'];    
    $sequencia_aleatoria=rand(0,$numero);

    connection::exec("insert into tab2(campo1,campo2,sequencia_aleatoria) values('$campo1','$campo2','$sequencia_aleatoria')");   
    unset($sequencia_aleatoria);    
}
  • That’s not what I need. I want it that way, if you have 100 records, it puts a random order from 0 to 100. Got it? As I explained, it needs to count the records and assign a random sequence without repeating.

  • Got it, I’ll fix the Cod.

  • That way he repeats rs

  • yes pq on your original Cod vc is inserting in db outside your foreach

  • still repeats, more than in the previous code.

  • I did not understand what repeats explains better

  • Repeats the value of the variable $sequential_random. I have 420 records, the number 1 for example was inserted 46 times.

  • The second example didn’t work. Set zero.

  • http://phpfiddle.org/lite?code=<? php n$count=420; // here iioria o Count($result); nfor($i=0;$i<=$count;$i++){ n Techo Rand(0,$count)." <br>"; n} n?>

  • copies all this in your browser Aki works. is so you use the same logic

  • Jasar, it worked if you set the Count value. But using Count($result) does not work. I also tried $Rows = $dads2->fetchAll(); $count = Count($Rows); And it didn’t work.

  • I believe that now the problem is in the array count

Show 7 more comments

2


Another option is to use the functions mt_rand to generate a random value and count to return the total of elements of array:

$dados2 = connection::select('SELECT * FROM tab1');

foreach ($dados2 as $reg) {   
    $campo1 = $reg['campo1'];
    $campo2 = $reg['campo2'];  

    $sequencia_aleatoria = mt_rand(0, count($dados2);  

    // Para inserir os dados de acordo com a linha atual
    connection::exec("insert into tab2(campo1,campo2,sequencia_aleatoria) values('$campo1','$campo2','$sequencia_aleatoria')");                    
}

Note: A second option may be the function mysqli_num_rows, to obtain the number of lines resulting from select, this way would not be necessary count($dados2).

Still, there is the possibility of generating repeated numbers.

Another way would be to generate a array with a range of numbers with range and use the function shuffle to mix the elements.

Something like that:

$dados2 = connection::select('SELECT * FROM tab1');
$linhas = $dados2->fetchAll();

$numeros = range(1, count($linhas));

shuffle($numeros); // Mistura os elementos

foreach ($linhas as $i => $linha) { 
    $campo1 = $linha['campo1'];
    $campo2 = $linha['campo2'];  

    $sequencia_aleatoria = $numeros[$i];

    // Para inserir os dados de acordo com a linha atual
    connection::exec("insert into tab2(campo1,campo2,sequencia_aleatoria) values('$campo1','$campo2','$sequencia_aleatoria')");                    
}
  • in the first example assigned zero to the variable. I gave an echo in the Insert, actually it assigned zero to all lines of the Insert

  • I’ll test your second example

  • Also not working. Assigns zero value.

  • Yes, they demand randomly

  • Amazingly enough, it shows the quantity records correctly.

  • I’ll try mysqli_num_rows

  • doesn’t work either :(

  • $lines = $dados2->fetchAll(); $count = sizeof($lines); echo $count; Exit; foreach ($dados2 as $reg) { for ($i = 0; $i <= $count; $i++) { $sequence = Rand(0, $count); }

  • I tried with sizeof and tbm did not. @stderr o for is correct. Because if I put a value in result it works. But using cont, it does not work. But if giving an echo works. Is it not because of the foreach. By not being inside the foreach?

  • Assigns zero as well. :'(

  • Yes, several zeros.

  • @Eduardosantos Opa is already something. Based on this code (http://ideone.com/akQhGp) below $sequencias_aleatorias = range(0, $contagem - 1) put a print_r($sequencias_aleatorias);, see what comes up! Obs: Delete previous comments if possible!

  • Array ( [0] => 1 [1] => 8 [2] => 6 [3] => 2 [4] => 4 [5] => 3 [6] => 5 [7] => 0 [8] => 7 )

  • @Eduardosantos Strange that this happens, you can put your code as it is on http://ideone.com and put the link here?

  • Dude see this: foreach ($dados2 as $reg) { $counts1 = Count($reg); $sequence = Rand(0, $counts1); It worked, but it did. How do I not repeat?

  • Please avoid long discussions in the comments; your talk was moved to the chat

Show 11 more comments

Browser other questions tagged

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