Jump to content

[SOLVED] Looping question: Creating a tale from an array


JPark

Recommended Posts

I can't figure out the loop logic on this one and would appreciate your help.

 

Say I have an array:

$test = array("first => this one", "second => that one", "third => the other one", ... "twentiest => the other other one");

 

And I want php to automatically generate a table that is 5 columns wide and 4 rows tall, populating it with the array items, how do I do it?

 

I can get all rows or all columns but not all of both.

 

Help?  Please and thank you.

 

Joe

Link to comment
Share on other sites

I don't know if you can get what you want from this.  This does 4 columns until it reaches the end

define ("NUMCOLS",4);

$res = mysql_query("SELECT id,thumb,cat FROM image WHERE cat='events'");

$count = 0;

echo "<table>";
while (list($id,$thumb,$cat) = mysql_fetch_row($res)) {

    if ($count % NUMCOLS == 0) echo "<tr>\n";  # new row
    echo "<td>stuff in here</td>\n";
    $count++;
    $counter++;

    if ($count % NUMCOLS == 0) echo "</tr>\n";  # end row
}

# end row if not already ended

if ($count % NUMCOLS != 0) {
   while ($count++ % NUMCOLS) echo "<td> </td>";
   echo "</tr>\n";
}
echo "</table>";

Link to comment
Share on other sites

But what if I wanted to use my array statement instead of querying the database?

 

$test = array("first => this one", "second => that one", "third => the other one", ... "twentiest => the other other one");

instead of

$res = mysql_query("SELECT id,thumb,cat FROM image WHERE cat='events'");

Link to comment
Share on other sites

try

<?php
$test = range(1,20);
$test = array_chunk($test, 5);
echo "<table>\n";
foreach ($test as $line) echo "<tr>\n\t<td>", implode("</td>\n\t<td>", $line), "</td>\n</tr>\n";
echo "</table>\n";
?>

 

Sasa, NICE!  One question... where/how would I specify MY array

 

$myarray = array("first => this one", "second => that one", "third => the other one", ... "twentiest => the other other one");

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.