PHP Create dynamic array from one SQL and Separate by a specified amount of record in another Array

Asked

Viewed 199 times

1

Boa Galera

I’m New in PHP and my Logica this Bad D+

I need to select (SQL) a list of Offerings and separate Offerings from 6 to 6 and then create the array containing the 6 Offerings Ids.

Code:

// SELECT DE FORMA RANDOMICA
$sql = "SELECT * FROM Oferta  ORDER BY RAND()";

//Seleciono todos as Ofertas
$totalOfertas = mysqli_query($conn, $sql);

// Conta o resultado do select  
$contaTotalOfertas = mysqli_num_rows($totalOfertas);

//defino a quantidade de registro por pagina
$quantidadePorPagina = 6;

// calcular o numero de pagina necessárias para apresentar as ofertas
$numeroPagina = ceil($contaTotalOfertas/$quantidadePorPagina);  

// Este Primeiro  Array traz a pagina 

for($i = 1; $i < $numeroPagina + 1; $i++){ 

    while($row = mysqli_fetch_assoc($totalOfertas)) {

        /* Aqui preciso armazenar os Ids das ofertas por paginas 
         * tipo Criar Dinamicamente os Array das paginas e armazenar as 6 Ofertas 
         */ em arrays.
    }
}
  • You want an array of arrays, with each sub array containing 6 ids (or less if you are finished)?

  • Yes that’s it I have to mount a Slider on the main page that has 6 record on the first slider and so susceptibly on the next ones

4 answers

1

You can create a two-dimensional array, better known as a matrix. For example, heading [0] [0] will be the first ID of the first 6 products, heading [0] [1] will be the second ID. So it goes until they’re all complete.

Try this way:

for($i = 1; $i < $numeroPagina + 1; $i++){
    while($row = mysqli_fetch_assoc($totalOfertas)){
        for($j = 0; $j <= $quantidade_de_produtos / 6; $j++){ // Aqui está dividido por 6 porque você vai dividir o array de 6 em 6
            for($k = 0; $k < 6; $k++){
                $matriz_de_ids[$j][$k] = $row['oferta_id'];
            }
        }
    }
}

Now just adapt your code according to the variables above.

1

I managed to do this way with the posted logic I added the function array_chunk

Error was in using While with the for was repeating everything

 for($j = 1; $j <= $contaTotalOfertas; $j++){ 
       $row = mysqli_fetch_assoc($totalOfertas);  

      $y = $j-1;
      $linha[$y] = $row["idOferta"];   

}

print_r(array_chunk($linha,6));

1

Simply, with a single loop, but two variables are required to store the indices, one is incremented every time with each iteration, the other is incremented by 6 in 6 iterations using the module operator (%):

$organized = [];

$data = [
["id" => 0],
["id" => 1],
["id" => 2],
["id" => 3],
["id" => 4],
["id" => 5],
["id" => 6],
["id" => 7],
["id" => 8]
];

$index = 0;

for ($i = 0; $i < count($data); $i++) {
    if ($i % 6 == 0) $index++;

    $organized[$index][] = $data[$i];
}

echo var_dump($organized);

In your case $data would be the result of SQL

0

First step completed the code was dry Now is mount the HTML.

 // SELECT
    $sql = "SELECT idOferta, NomeOferta  FROM Oferta ORDER BY RAND() ";
    //Seleciono todos os Produtos   
    $totalOfertas = mysqli_query($conn, $sql);
    // Conta o resultado do select  
    $contaTotalOfertas = mysqli_num_rows($totalOfertas);
    //defino a quantidade de registro por pagina
    $qdtOfertasPorPagina = 6;

    //Crio o Array de um SELECT 
    for ($ofertas = array (); $row = $totalOfertas->fetch_assoc(); $ofertas[] = $row);
    // Divido pelo numero de Paginas 
    $paginas_Oferta  = array_chunk($ofertas, $qdtOfertasPorPagina);

    print_r($paginas_Oferta);

Browser other questions tagged

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