Group elements of an array during a loop in php

Asked

Viewed 97 times

0

Good evening guys, I come with one more question in a loop in php.

I need to create a PDF of a very extensive report. An alternative that the MPDF itself indicates, is to create blocks and go writing the pages one by one. It will be an overload but, I need to generate a pdf, with a report that can have up to 100 thousand records (I intend to display 100 per page or go adapting), so the MPDF can not receive all html at once.

The point is that I have an array, where each index receives a row of data (a tag <tr>) which I receive from the database. But I wanted to group this into blocks of 100 for example, ie each index, group 100 lines.

My current array follows this format

$tr = [
  0 => "<p>Valor 1</p>",
  1 => "<p>Valor 2</p>",
  2 => "<p>Valor 3</p>",
  3 => "<p>Valor 4</p>",
  4 => "<p>Valor 5</p>",
  ...
];

In the example above, if it were for example 2 elements per index, I would need it to look like this:

$tr = [
  0 => "<p>Valor 1</p> <p>Valor 2</p>",
  1 => "<p>Valor 3</p> <p>Valor 4</p>",
  2 => "<p>Valor 5</p>" ... 
];

I tried to make a loop, which looks more like a gambiarra, but gives some index errors and ends up losing some elements, what I tried was this:

$group = [];
for($i = 0; $i <= count($tr); $i++) {       
    for($i2 = 0; $i2 < 100; $i2++) {
        $group[$i] .= $tr[$i2];
        unset($tr[$i2]);
    }
    $tr = array_values($tr);
}

What I tried to do is, with each loop loop loop, fill up to 100, and the loop of the second is I make an unset by cleaning that variable, so when I exit the down and go to the next outside loop, rearrange the array without the items that have already been accounted for.

Someone can help me with this logic. I’m not able to think of a clean way and form it

1 answer

1


You can use the function array_chunk() to break your array into blocks of 100 elements. Each of these blocks you can group its elements using the function implode() that joins elements of an array into a string.

In the example I created an array $tr containing 731 elements <p> and applied the reasoning described above.

<?php
//Cria um array com 731 elementos para o exemplo.
for($i=1;$i<=731;$i++){
  $tr[]="<p>Valor $i</p>";
}

//Quebra o array em blocos de 100 elementos e itera sobre eles.
foreach(array_chunk($tr, 100) as $item){
  $resultado[]= implode($item); //Agrupa cada bloco em uma string e a adiciona ao resultado.
}

print_r($resultado);

Test the code on Repl.it

Browser other questions tagged

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