Aaqib Mehran
Aaqib Mehran

Reputation: 41

How to divide sql result into four equal parts in PHP?

I have all the States of united states in the database table. I want to get them all in a query and devide them in 4 equal parts and show in 4 bootstrap columns. How to do it in php? Output Screen :

enter image description here

Upvotes: 0

Views: 825

Answers (1)

Alok Patel
Alok Patel

Reputation: 8022

You can use array_chunk() function to split an array into chunks. You can decide the size of each chunk.

array_chunk() accepts two parameter, first one is the array variable and second is the size of each chunk.

To decide the size of each chunk divide the total number of array elements by 4. Here is how you get the chunk size,

<?php

$states=array("A", "b", ...);
$totalstates=count($states);
$chunksize=$totalstates/4;

Now use this $chunksize to create 4 different arrays.

Like this,

<?php

$fourarrays=array_chunk($states, $chunksize);
print_r($fourarrays);

Above code will create an array with four elements each having an array of states.

Now use them to fill the content of each bootstrap column.

Upvotes: 1

Related Questions