hjaffer2001 hjaffer2001 -4 years ago 58
MySQL Question

PHP Looping and foreach

I will explain my problem with a single example.


  1. I have a set of email ids (fetch from db and it will be dynamic). Let us say there are 100 email ids

  2. I need to group them with a count of 10. In other words, 100 email ids divided by 10 => So there will be 10 loops.

  3. The output should look like



Group1:
---first ten email ids---

Group2:
---next ten email ids---
. . . . ..

Group3:
---last ten email ids---

Here is my php code(i have revised/corrected my code)

<?php
$con=mysql_connect("localhost","root","admin");
mysql_select_db("test1",$con);
$sel=mysql_query("SELECT DISTINCT emailaddress FROM userlist");
while($row=mysql_fetch_array($sel))
{
$mail[]=$row['emailaddress'];
}


$chunk = array_chunk($mail, 10);
$get_chunk_count = count($chunk);


for($i=0;$i<$get_chunk_count;$i++){
echo "Group :".$i;
echo "<br>";
echo "========";
echo "<br>";
$count_inside_count = count($chunk[$i]);

for($j=0;$j<=$count_inside_count;$j++){
echo "<pre>";
echo $chunk[$i][$j];
echo "</pre>";
}
}
?>


EDITED: The above code works fine, and i have edited. Thanks for all the help :)

Answer Source

You could make use of PHP's array_chunk() function to break your array up into smaller chunks.

Not tested but it should be pretty close I think.

$chunk = array_chunk($mail, 10);
$i = 0;
do
{
    echo $chunk[$i] . '<br />';
    $i++;
    if($i == 10)
        sleep(10);
} while ($i < count($chunk)); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download