Jump to content

foreach or while - table columns and rows


sigmahokies

Recommended Posts

Hi everyone,

 

I am still learning to write the code in PHP, it is not easy. I am learning how to use foreach and while array, but I haven't figured how to create the two or more columns, only I can do one column. Soon, I will have larger database coming in, I need to learn how to create few columns, instead of one column. Can anyone help me? not following in row, I rather to follow by columns. 

 

Thanks,

Gary

Link to comment
Share on other sites

You talk about 'using' the foreach and while operators but then you talk about columns. Don't understand.

 

Those two operators allow you to easily iterate through a collection of "data" easily. Each time thru you can process one piece of that data. To show you:

 

If you have an array of the following: $ar = array('apple', 'pear', 'peach', 'cherry')

 

and you use a foreach on it like this: foreach ($ar as $a)

 

then the code you follow that statement with would operate on $a and you could do something like:

 

foreach ($ar as $a)

echo $a."<br>";

 

Or if you had an array like $ar = array('val1'=>12, 'val2'=>15,'val22'=>22, 'val33'=>29)

you could do this:

 

foreach ($ar as $k=>$v)

echo "Item $k contains $v<br>";

 

and the output would look like:

Item val1 contains 12

Item val2 contains 15

Item val22 contains 22

Item val33 contains 29

 

The while loop is a bit different in that it works well on arrays of arrays (imho). Usually when retrieving a set of query results as an associative array (or numeric too) you would do this:

 

$q = 'select firstname, lastname, street1, city, state,zip from address_table where city='Albany'";

$qresults = $pdo->query($q);

while ($row = $qresults->fetch(PDO::FETCH_ASSOC)

{

echo "{$row['firstname']" {$row['lastname']} lives at {$row['street1'} {$row['city']} {$row['state']} {$row['zip']}<br>";

 

which would echo each row of the query results on a single line of your screen.

 

As you can see the two operators work on whatever data you give them, so your question about "adding columns" doesn't seem relevant here.

 

Hope this helps.

Link to comment
Share on other sites

If you are working with an array, you should almost always use foreach(). As ginerjm showed, a while() loop is typically used for scenarios like processing data from a query result - where you want the loop to continue until some specific condition occurs.

 

As to the question about columns, I think I understand what you are trying to do. The implementation is pretty similar whether you are using an array or DB results. But, how do you want the data displayed in columns? Left to right going down OR top to bottom going to the right? The former is very easy and the latter is a little more difficult, but definitely achievable. Here is some sample code:

<?php
 
//Define number of columns
$columns = 4;
 
$query = "SELECT field1, field2
          FROM table_name
          ORDER BY field1";
$results = $pdo->query($query);
//Put results into an array
$records = array();
while ($row = $results->fetch(PDO::FETCH_ASSOC)
{
    $records[] = $row;
}
 
//Split array into chunks based on column size
$rows = array_chunk($records, $columns);
 
//Create Output for the rows of records
$output = "";
foreach($rows as $row)
{
    $output .= "<tr>\n";
    foreach($row as $record)
    {
     $output .= "<td>{$record['field1']}<br>{$record['field2']}<td>\n";
    }
    $output .= "</tr>\n";
}
 
?>
 
<table>
<?php ech
Edited by Psycho
Link to comment
Share on other sites

ginerjm and psycho,

 

ginerjm, All right, my apology if I don't make you understand. my purpose to ask anyone to see if anyone know how to do code in array into few columns, I can do one column. I am trying to have start with top, then down till 10th row, then go to other column with start with top, then go on till 10th row, continue. But I can increase number of row in column if necessary because I will have almost 200 names on database that I don't want to have their name in one column that can make long column on website, so I will like to have 4 or 5 columns to make less long column on website. Do you follow me? If not, my apology because my writing in grammar in English is my second language because I am Deaf, ASL is my first language as usual. Thank you for be patient with me.

 

Psycho, I am still learning, I have been research around about PHP language, there are some I don't understand how it works, example - =>, =<, $i++, \n, %s, %n, \s...I haven't understand complete, but I am still progress to understand them.

Link to comment
Share on other sites

So you were talking about output layout and not the 'handling of foreach/while'. Now it is clear.

 

The difficulty with this is the layout. I have done this using an html table but don't remember how at the moment. Another way would be to define a div to hold the data for each column and then to output your results into the appropriate div and then just display the divs side-by-side. In your while loop keep track of which column you need to put this row's result into and then increment that counter. Read up on variable variables in the manual - they would work well for this

Link to comment
Share on other sites

As I stated, having record go from top down, then from left to right in columns is a little more difficult - but achievable. You state you want to do this from an array, but then you state this is from a database. It helps if you are clear on the source data - database. You can put the database results into an array, but it is not always necessary. So, try not to make assumptions that the data would have to be put into an array first. There are always multiple ways to do the same thing. Here is some sample code that should do what you need.

 

 

<?php
 
//Define number of columns
$columns = 4;
 
$query = "SELECT lastname, firstname
          FROM table_name
          ORDER BY lastname, firstname";
$results = $pdo->query($query);
//Put results into an array
$records = array();
while ($row = $results->fetch(PDO::FETCH_ASSOC)
{
    $records[] = $row;
}
 
//Calculate the number of rows per column
$rows = ceil(count($records) / $columns);
 
//Create Output for the rows of records
$output = "";
for($row=0; $row<$rows; $row++)
{
    $output .= "<tr>\n";
    for($col=0; $col<$columns; $col++)
    {
        //Determine the index from the records array
        $idx = $row + ($col * $rows);
        //Prepare the content based on whether the index exists
        // - last row may not have records in all columns
        $content = isset({$records[$idx]) ? "{$records[$idx]['lastname']}, {$records[$idx]['firstname']}" : '';
        $output .= "    <td>{$content}<td>\n";
    }
    $output .= "</tr>\n";
}
 
?>
 
<table>
<?php echo $output; ?>
</table>
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.