TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 03-06-2008, 02:26 PM   #1 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default Best Way To Loop In A Table?

Hi all,

I'm wondering what the best way to loop in a table is? I'm pulling data from a database and want it to display like this:


The only way I know how to do it is by making separate looks for each column like so:

PHP Code:
<table style="float:left;margin:0 15px;">
<?php
  
//Creates a loop that shows all of the data where category = rock
   
$i 0;
   
$times1 4;
   while (
$i $times1
   {
      
$category_artist_rock mysql_result($rock_result$i"cd_artist");            
                                    
?>
     <tr>
       <td style="font-size:12px;">
          <a href="<?php echo $category_artist_rock ?>"><?php echo $category_artist_rock?></a>
       </td>
     </tr>

<?php  
  $i
++;
  }
?>
</table>
                                    
<table style="float:left;margin:0 15px;">
<?php
  
//Creates a loop that shows all of the data where category = rock
   
$i 4;
   
$times1 8;
   while (
$i $times1
   {
      
$category_artist_rock mysql_result($rock_result$i"cd_artist");            
                                    
?>
     <tr>
       <td style="font-size:12px;">
          <a href="<?php echo $category_artist_rock ?>"><?php echo $category_artist_rock?></a>
       </td>
     </tr>

<?php  
  $i
++;
  }
?>
</table>
Above is the code for displaying two columns with four pieces of table data in each. If I wanted four columns I would have to do this four times. I think this is a very ugly way to do it and is probably using a lot more code than is needed. I know there's a simpler way but I can't think of one.

Thanks in advance,
Steven
__________________
My Personal and Photo Blog
StevenF is offline  
Reply With Quote
Old 03-06-2008, 03:32 PM   #2 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Hi Steven,

Take a look at the array_chunk() function. Specificly, take a look at this comment - PHP: array_chunk - Manual - it gives an example on how to do exactly what you want to do

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
The Following 3 Users Say Thank You to Alan @ CIT For This Useful Post:
Nor (03-06-2008), ReSpawN (03-06-2008), StevenF (03-06-2008)
Old 03-06-2008, 03:57 PM   #3 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

Thanks again, Alan. I tried taking the code and modifying it a little, but I don't know much about arrays - I will read more in-depth soon.

The example:

PHP Code:
<?php

$values 
range(131);
$rows array_chunk($values7);

print 
"<table>\n";
foreach (
$rows as $row) {
    print 
"<tr>\n";
    foreach (
$row as $value) {
        print 
"<td>" $value "</td>\n";
    }
    print 
"</tr>\n";
}
print 
"</table>\n";

?>
$rows as $row not sure what that means, $row is specified anywhere.

I tried:

PHP Code:
<?php
  
//Create a query to display the ROCK artist in the category section

  
$rock_category 'SELECT * FROM products WHERE cd_category = "rock"';
  
$rock_result mysql_query($rock_category);

  
$num_rock mysql_numrows($rock_result);

  
$category_artist_rock mysql_result($rock_result"cd_artist");


$rows array_chunk_vertical($category_artist_rock7);

print 
"<table>\n";
foreach (
$rows as $row) {
    print 
"<tr>\n";
    foreach (
$row as $category_artist_rock) {
        print 
"<td>" $category_artist_rock "</td>\n";
    }
    print 
"</tr>\n";
}
print 
"</table>\n";

?>
I know that's completely wrong and I need to add $num_rock in there somewhere. Just not sure where. I think I need to study this more.

Also tried:

PHP Code:
<?php
  $values 
range(1$num_rock);
  
$rows array_chunk_vertical($values7);

  print 
"<table>\n";
  foreach (
$rows as $row
  {
     print 
"<tr>\n";

     foreach (
$row as $value
     {
         print 
"<td>" $value "</td>\n";
     }

     print 
"</tr>\n";
}

  print 
"</table>\n";
?>
But now I need to put the actual values I want to output in somewhere - $category_artist_rock
__________________
My Personal and Photo Blog
StevenF is offline  
Reply With Quote
Old 03-06-2008, 04:18 PM   #4 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Hi Steven,

Here's a little cut/paste example and the results it displays

PHP Code:
<?php

$items 
= array(
    
'One',
    
'Two',
    
'Three',
    
'Four',
    
'Five',
    
'Six',
    
'Seven',
    
'Eight',
    
'Nine',
    
'Ten',
    
'Eleven',
    
'Twelve',
    
'Thirteen',
    
'Fourteen',
    
'Fifteen',
    
'Sixteen',
    
'Seventeen',
);

function 
array_chunk_vertical($input$size$preserve_keys false$size_is_horizontal true)
{
    
$chunks = array();
    
    if (
$size_is_horizontal) {
        
$chunk_count ceil(count($input) / $size);
    } else {
        
$chunk_count $size;
    }
    
    for (
$chunk_index 0$chunk_index $chunk_count$chunk_index++) {
        
$chunks[] = array();
    }

    
$chunk_index 0;
    foreach (
$input as $key => $value)
    {
        if (
$preserve_keys) {
            
$chunks[$chunk_index][$key] = $value;
        } else {
            
$chunks[$chunk_index][] = $value;
        }
        
        if (++
$chunk_index == $chunk_count) {
            
$chunk_index 0;
        }
    }
    
    return 
$chunks;
}

$rows array_chunk_vertical($items4);

print 
"<table border=\"1\">\n";
foreach (
$rows as $row) {
    print 
"<tr>\n";
    foreach (
$row as $value) {
        print 
"<td>" $value "</td>\n";
    }
    print 
"</tr>\n";
}
print 
"</table>\n";


This example uses an array called $items but changing it to your mysql data should be fairly easy. Changing $items block of code to something like the following should work:

PHP Code:
$query "SELECT cd_artist FROM products WHERE cs_category = 'rock'";
$result mysql_query($query);

$items mysql_fetch_array($result); 
This code only fetches the cd_artist column but you can add more columns there as required.

Alan
Attached Thumbnails
best-way-loop-table-displaytable.jpg  
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
The Following 2 Users Say Thank You to Alan @ CIT For This Useful Post:
SOCK (03-06-2008), StevenF (03-06-2008)
Old 03-06-2008, 05:11 PM   #5 (permalink)
Nor
The Addict
 
Join Date: Nov 2007
Posts: 282
Thanks: 61
Nor is on a distinguished road
Default

Thanks for telling me about array_chunk, never had a use for it in that way :).
__________________
PHP/XHTML Freelancer:
Cleanscript.com v3 - Programming starting at just $5 act now!
Nor is offline  
Reply With Quote
Old 03-06-2008, 05:47 PM   #6 (permalink)
The Frequenter
 
ReSpawN's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 460
Thanks: 49
ReSpawN is on a distinguished road
Default

Same here, thanks Alan.
__________________
"Life is a bitch, take that bitch on a ride"
Send a message via MSN to ReSpawN
ReSpawN is offline  
Reply With Quote
Old 03-06-2008, 05:49 PM   #7 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

All hail Alan I'll give that a shot later, thanks!
__________________
My Personal and Photo Blog
StevenF is offline  
Reply With Quote
Old 03-06-2008, 06:04 PM   #8 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

No probs, glad it helped you all

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
Old 03-06-2008, 06:37 PM   #9 (permalink)
The Frequenter
 
ReSpawN's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 460
Thanks: 49
ReSpawN is on a distinguished road
Default

It sure did heh. I've noticed a long time ago that there are various functions with the array_ function but I've never tried them out, or looked them up to what they do exactly.

++ Hint ++ Alan -> Make an article...?
__________________
"Life is a bitch, take that bitch on a ride"
Send a message via MSN to ReSpawN
ReSpawN is offline  
Reply With Quote
Old 03-06-2008, 06:46 PM   #10 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Quote:
Originally Posted by ReSpawN View Post
++ Hint ++ Alan -> Make an article...?
I'll add it to the list

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
Old 03-06-2008, 09:20 PM   #11 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

Well... it kind of works

I'm using this code:

PHP Code:
<?php

        $category_rock 
'SELECT cd_artist FROM products WHERE cd_category = "rock"';
        
$rock_result mysql_query($category_rock);
        
        
$items mysql_fetch_array($rock_result);  
        
        function 
array_chunk_vertical($input$size$preserve_keys false$size_is_horizontal true)
        {
            
$chunks = array();
            
            if (
$size_is_horizontal) {
                
$chunk_count ceil(count($input) / $size);
            } else {
                
$chunk_count $size;
            }
            
            for (
$chunk_index 0$chunk_index $chunk_count$chunk_index++) {
                
$chunks[] = array();
            }
        
            
$chunk_index 0;
            foreach (
$input as $key => $value)
            {
                if (
$preserve_keys) {
                    
$chunks[$chunk_index][$key] = $value;
                } else {
                    
$chunks[$chunk_index][] = $value;
                }
                
                if (++
$chunk_index == $chunk_count) {
                    
$chunk_index 0;
                }
            }
            
            return 
$chunks;
        }
        
        
$rows array_chunk_vertical($items4);
        
        print 
"<table border=\"1\">\n";
        foreach (
$rows as $row) {
            print 
"<tr>\n";
            foreach (
$row as $value) {
                print 
"<td>" $value "</td>\n";
            }
            print 
"</tr>\n";
        }
        print 
"</table>\n"
?>
And it's giving me this result:



But my table looks like this:



It seems to be returning only the first artist with the category "rock", and it's showing it twice for some reason.
__________________
My Personal and Photo Blog
StevenF is offline  
Reply With Quote
Old 03-06-2008, 09:28 PM   #12 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Hi Steven,

Can you add:

PHP Code:
var_dump($items); var_dump($rows); 
To the end of your code, refresh the page, then paste the results here?

Thanks,
Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
Old 03-06-2008, 09:40 PM   #13 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
Alan @ CIT is on a distinguished road
Default

oops, my fault - I had a blond moment I'm so used to Zend_Db's fetchAll() method that I forgot that mysql_fetch_array() only returns the first result and that you have to loop through it to get them all

Remove the mysql_fetch_array() line and replace it with this:

PHP Code:
while ($item mysql_fetch_array($rock_result))
{
    
$items[] = $item['cd_artist'];

Hopefully that should work this time

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
The Following User Says Thank You to Alan @ CIT For This Useful Post:
StevenF (03-06-2008)
Old 03-06-2008, 09:40 PM   #14 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

I knew it was something to do with mysql_fetch_array and loops. I was messing around but couldn't get anything to work. Thank you very much for that, Alan.
__________________
My Personal and Photo Blog
StevenF is offline  
Reply With Quote
Old 03-12-2008, 01:15 PM   #15 (permalink)
The Contributor
 
abiko's Avatar
 
Join Date: Feb 2008
Location: Croatia
Posts: 90
Thanks: 4
abiko is on a distinguished road
Default

Just an addition.
I wanted to loop horizontaly - and add empty colums where needed.
so -

Code:
 1 2 3 4 
 5 6 7 8
 9 e e e
(e stands for empty column)

So here is a simple code for that :)
PHP Code:
<?php
  $data 
range117 );
  
$out array_chunk($data4) ;
  
  
// Check the data 
function addEmptyColumn$array ) {
  foreach  ( 
$array as $a => $r ) {  
        
$c count$r );
        if ( 
$c 4) {           
            
$loop 4-$c;              
            for( 
$i=1$i<=$loop$i++) {
                    
$r[] = '';  
            }
        }
       
$kr[] = $r;                
  }
  return 
$kr;
}

// Final output
$final addEmptyColumn$out );

?>
The table loop:
PHP Code:
<table width="300">
<?php foreach( $final as $row => $data ) { ?>
<tr>
    <?php foreach( $data as $column ) { 
        if ( empty(
$column) ) $column "&nbsp;";
    
?>
        <td><?php echo $column?></td>
    <?php ?> 
</tr>
<?php }?>
</table>
Output:
HTML Code:
<table width="300">
<tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
     
</tr>

<tr>
            <td>5</td>
            <td>6</td>
            <td>7</td>
            <td>8</td>
     
</tr>
<tr>
            <td>9</td>

            <td>10</td>
            <td>11</td>
            <td>12</td>
     
</tr>
<tr>
            <td>13</td>
            <td>14</td>

            <td>15</td>
            <td>16</td>
     
</tr>
<tr>
            <td>17</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>

     
</tr>
</table>
Hope this helps anybody. :D
__________________
Back from sysadmins to the programmers.
Send a message via ICQ to abiko Send a message via MSN to abiko
abiko is offline  
Reply With Quote
Old 03-13-2008, 09:10 PM   #16 (permalink)
The Wanderer
 
Join Date: Nov 2007
Posts: 9
Thanks: 1
solistus is on a distinguished road
Default

I apologise if this has already been said, but it looks like nobody ever answered this question from the OP:

Quote:
$rows as $row not sure what that means, $row is specified anywhere.
So I'll go ahead.

The line in question was foreach($rows as $row). Foreach is a very useful looping construct that only works with an array. The first variable is the name of the array and the second is the name that each element in that array will have.

Let's say I have the following array storing information about my family:

PHP Code:
$myFamily = array(=> "brother"=> "mother"=> "father"=> "cat"); 
I want to loop through the array and print out all the values. I could do something like this (and if you've coded in, say, Java, you're probably used to having to do things like this):

PHP Code:
for($i 0$i count($myFamily); $i++)
{
  echo 
$myFamily[$i] . "<br />";

Instead, you can do this:

PHP Code:
foreach($myFamily as $familyMember)
  echo 
$familyMember "<br />"
Well, that's nicer looking, but so what? It doesn't do anything good old for() can't do just as easily... right?

Well, let's say that instead of just numeric indices, our family array has names linked to family position:

PHP Code:
$myFamily = array("John" => "brother""Linda" => "mother""James" => "father""Whiskers" => "cat"); 
Yikes, so much for counting up a temporary looping variable! Luckily, foreach makes this entirely painless. foreach($x as $y) ignores the indices and just gives you the values in order, each time as $y. However, there's another way to use foreach:

PHP Code:
foreach($myFamily as $name => $position)
 echo 
$name " is my " $position ".<br />"
Doesn't get much easier than that, does it? This example is fairly trivial, but the more complex things you're doing with arrays, the handier foreach becomes. Hope this helps!
solistus is offline  
Reply With Quote
The Following User Says Thank You to solistus For This Useful Post:
StevenF (03-14-2008)
Old 03-14-2008, 04:26 PM   #17 (permalink)
The Contributor
 
Join Date: Jan 2008
Posts: 87
Thanks: 49
StevenF is on a distinguished road
Default

Thanks a lot, Solistus. Great explanation!
__________________
My Personal and Photo Blog
StevenF is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 11:22 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design