TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Best Way To Loop In A Table? (http://www.talkphp.com/absolute-beginners/2426-best-way-loop-table.html)

StevenF 03-06-2008 02:26 PM

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

Alan @ CIT 03-06-2008 03:32 PM

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

StevenF 03-06-2008 03:57 PM

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

Alan @ CIT 03-06-2008 04:18 PM

1 Attachment(s)
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

Nor 03-06-2008 05:11 PM

Thanks for telling me about array_chunk, never had a use for it in that way :).

ReSpawN 03-06-2008 05:47 PM

Same here, thanks Alan. :-)

StevenF 03-06-2008 05:49 PM

All hail Alan ;-) I'll give that a shot later, thanks!

Alan @ CIT 03-06-2008 06:04 PM

No probs, glad it helped you all :-)

Alan

ReSpawN 03-06-2008 06:37 PM

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...? :-P

Alan @ CIT 03-06-2008 06:46 PM

Quote:

Originally Posted by ReSpawN (Post 12047)
++ Hint ++ Alan -> Make an article...? :-P

I'll add it to the list :-D

Alan

StevenF 03-06-2008 09:20 PM

Well... it kind of works :-D

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.

Alan @ CIT 03-06-2008 09:28 PM

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

Alan @ CIT 03-06-2008 09:40 PM

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

StevenF 03-06-2008 09:40 PM

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.

abiko 03-12-2008 01:15 PM

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

solistus 03-13-2008 09:10 PM

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!

StevenF 03-14-2008 04:26 PM

Thanks a lot, Solistus. Great explanation!


All times are GMT. The time now is 10:50 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0