PHP: array - for every 4, "do this"?

Hitman
Soldato
Joined
25 Feb 2004
Posts
2,837
Hi,

Having a bit of a problem. I'm storing a bunch of data and retrieving it with mssql_fetch_array, and outputting it like so:


Code:
(code goes here to retrieve the details)

<table>

while( $row = mssql_fetch_array( $query ) )
{

	$type = $row["pm_type"];
	$id = $row["pm_id"];
	$name = $row["pm_name"];
	$img = $row["img"];
	$img_full = $row["img"] . "_full";
	$AP = SomeFunction( $type, $id );
	
	echo "<td>whatever here</td>";
}

</table>
What I'm trying to do is output 4 results per table, and then make another table if there's already 4 results in the previous table. Obviously with the above code I can't do that because the while puts it all inside one table.

Hope that's clear, and hope someone can help!

Cheers in advanced
 
How about:
PHP:
<?php
$loopCount = 0;

while( $row = mssql_fetch_array( $query ) )
{
    if ($loopCount % 4 == 0) {
        if ($loopCount > 0) {
             echo("</table>");
        }
        echo("<table>");
    }
    $type = $row["pm_type"];
    $id = $row["pm_id"];
    $name = $row["pm_name"];
    $img = $row["img"];
    $img_full = $row["img"] . "_full";
    $AP = SomeFunction( $type, $id );
    
    echo "<tr><td>Row ".$loopCount."</td></tr>";
}
echo("</table>");
?>

I haven't tested this, just written it out whilst copying some data. Beware, i'm tired, so it could completely fall apart. The key bit though is the % sign. This signifies the modulus operator (http://us.php.net/operators.arithmetic). Basically, if the remainder of the loop counter divided by the number of cells you want (4 in this case) is zero, this should start a new table. It should also end the previous table, assuming one has been started (hence the $loopCount > 0 bit).

Hopefully, that will give you some pointers.

Matt
 
Hi,

Managed to come up with this based on your code, feenster99:

Code:
$loop = 0;

while( $row = mssql_fetch_array( $query ) )
{
	if( $loop == 4 )
	{
		echo "</table>";
		$loop = 0;
		echo "<table>";
	}
	
	$loop++;

	echo "<td>whatever here</td>";
}
Yours didn't seem to work properly (excused though considering you were tired :p) but based on yours I've managed to cook that up and seems to work :)

Cheers
 
Yours will only work once—i.e. after 4 results, not after every 4 results. Change your $loop == 4 to $loop % 4 == 0.

(feenster's didn't work because he never incremented $loopCount, fyi.)
 
Blah, forgot about incrementing the counter. I tend to use for () {} loops anyway, so that's taken care of. My bad.

Glad to see you found a resolution though.

Matt
 
Yours will only work once—i.e. after 4 results, not after every 4 results. Change your $loop == 4 to $loop % 4 == 0.

(feenster's didn't work because he never incremented $loopCount, fyi.)

Actually it should work properly because he's resetting the counter on every fourth iteration.
 
Back
Top Bottom