Page 1 of 1

Need help to print an array to a html table

Posted: Fri Apr 16, 2010 9:22 pm
by StRoYeR
Hi all, I need to convert an array to a table (just for trying to learn a little bit more about PHP programming)
I thought it could be a good idea to print a simple array with animals and then printing them into a html table ordering them by family name.

If I want to print an array like this:

Code: Select all

<?
  $Categories = array("Equidae", "Canis lupus familiaris", "Psittacidae");

//How do I store here the names of the animals? 

?>
-----------------------------------------------------------------------------------
| Equidae | Canis lupus familiaris | Psittacidae
=====================================================
| Some image | Some image | Some image
=====================================================
| Hipparion | Shi tzu | Lovebird
------------------------------------------------------------------------------------
| Mesohippus | German Collie | Blue-and-gold Macaw
------------------------------------------------------------------------------------
| Hyracotherium | Doberman Pinscher | Scarlet Macaw
-----------------------------------------------------------------------------------
| (Empty) | French Mastiff | (Empty)
----------------------------------------------------------------------------------

This is where I arrived so far...

Code: Select all

                                  <table>

                                    <tr>
<?
  foreach ($Categories as $Category) {
					echo "                                      <th>".$Category."</th>\n";
  }
?>

                                    </tr>

                                    <tr>
<?
//Here I want to display, for example, an image
  foreach ($ImgCategories as $ImgCategory) {
      echo '                                      <td><img src="'.$ImgCategory.'" width="50px" height="50px" /></td>'."\n";
  }
?>

                                    </tr>

//I think I should use another "foreach" to display the names of the animals... How do I implement it?
Thanks in advance.

Regards.

StRoYeR

Re: Need help to print an array to a html table

Posted: Sat Apr 17, 2010 1:15 am
by mrcoffee
I've found with PHP (as with many things) that there are usually many ways to get same result. While the flexibility is nice, it sometimes frustrates me by leaving me wondering if there's a "better" way I could have coded something.

With that said, below are a just a couple of ways you could build this table. I do not claim that they're the most efficient, but hopefully useful for learning.

One thing I would do is keep your data sets related.

It's fine to have

Code: Select all

$Categories = array('Equidae','Canis lupus familiaris','Psittacidae');
but if you use

Code: Select all

$ImgCategories = array('equid.jpg','canis.jpg','psitt.jpg');
then you'd have to make sure the order is always the same. This is probably okay for a couple of items, but when you start working with larger sets or sets with dynamic input (from a form or database, for example), you'll want to make sure that the sets of data can relate.

One way to relate the data is by using associative arrays. Using the print_r command with $Categories would show:
[text]Array
(
[0] => Equidae
[1] => Canis lupus familiaris
[2] => Psittacidae
)[/text]

But, you can also make an array as follows:

Code: Select all

$associative_array = array('one'=>'One','hello'=>'world','foo'=>'bar');
which, using print_r again gives:
[text]Array
(
[one] => One
[hello] => world
[foo] => bar
)[/text]

Here is one way of getting the table with associative arrays:

Code: Select all

<?php

$Categories = array('Equidae','Canis lupus familiaris','Psittacidae');

$Images['Equidae'] = 'equidae.jpg';
$Images['Canis lupus familiaris'] = 'canis.jpg';
$Images['Psittacidae'] = 'psitt.jpg';

// $Examples will be similar to $Images, but instead of an image name, we use an array;
$Examples['Canis lupus familiaris'] = array();
$Examples['Canis lupus familiaris'][] = 'Shi tzu'; // $arr[] tells PHP to add an array element with a sequential key (starting with 0)
$Examples['Canis lupus familiaris'][] = 'German Collie';
$Examples['Canis lupus familiaris'][] = 'Doberman Pinscher';
$Examples['Canis lupus familiaris'][] = 'French Mastiff';

$Examples['Equidae'] = array('Hipparion','Mesohippus','Hyracotherium'); // just another way
$Examples['Psittacidae'] = array('Lovebird','Blue-and-gold Macaw','Scarlet Macaw');

/*
print_r($Examples); // outputs (just for reference in this post...):
Array
(
    [Canis lupus familiaris] => Array
        (
            [0] => Shi tzu
            [1] => German Collie
            [2] => Doberman Pinscher
            [3] => French Mastiff
        )

    [Equidae] => Array
        (
            [0] => Hipparion
            [1] => Mesohippus
            [2] => Hyracotherium
        )

    [Psittacidae] => Array
        (
            [0] => Lovebird
            [1] => Blue-and-gold Macaw
            [2] => Scarlet Macaw
        )

)
*/

// we could even sort the categories here, and the images and examples will stay matched in the table
sort($Categories);
?>

<table border="1" cellpadding="5">
	<tr>
	<?php foreach($Categories as $Category): ?>
		<th><?php print $Category; ?></th>
	<?php endforeach; ?>
	</tr>
	
	<tr>
	<?php foreach($Categories as $Category): // notice that $Categories is the "master" list; it determines what columns go where, rather than depending on $Images to be in the correct order. ?>
		<td>
			<?php if(isset($Images[$Category])): ?>
				<img src="<?php print $Images[$Category]; ?>" />
			<?php endif; ?>
		</td>
	<?php endforeach; ?>
	</tr>
	
	<?php for($row = 0; $row < count(max($Examples)); $row ++): // make as many rows as the set with the greatest number of examples. ?>
	<tr>
		<?php foreach($Categories as $Category): ?>
			<td><?php print $Examples[$Category][$row]; ?></td>
		<?php endforeach; ?>
	</tr>
	<?php endfor; ?>
	
</table>
?>
And here's another method:

Code: Select all

<?php

unset($Categories);

$Categories = array(
	'Equidae' => array(
		'image' => 'equidae.jpg',
		'examples' => array(
			'Hipparion','Mesohippus','Hyracotherium'
		)
	),
	'Canis lupus familiaris' => array(
		'image' => 'canisLupusFamiliaris.jpg',
		'examples' => array(
			'Shi tzu','German Collie','Doberman Pinscher','French Mastiff'
		)
	)
);
$Categories['Psittacidae'] = array();
$Categories['Psittacidae']['image'] = 'psittacidae.jpg';
$Categories['Psittacidae']['examples'] = array('Lovebird');
$Categories['Psittacidae']['examples'][] = 'Blue-and-gold Macaw';
$Categories['Psittacidae']['examples'][] = 'Scarlet Macaw';

/*
print_r($Categories); // results in:
Array
(
    [Equidae] => Array
        (
            [image] => equidae.jpg
            [examples] => Array
                (
                    [0] => Hipparion
                    [1] => Mesohippus
                    [2] => Hyracotherium
                )
        )

    [Canis lupus familiaris] => Array
        (
            [image] => canisLupusFamiliaris.jpg
            [examples] => Array
                (
                    [0] => Shi tzu
                    [1] => German Collie
                    [2] => Doberman Pinscher
                    [3] => French Mastiff
                )
        )

    [Psittacidae] => Array
        (
            [image] => psittacidae.jpg
            [examples] => Array
                (
                    [0] => Lovebird
                    [1] => Blue-and-gold Macaw
                    [2] => Scarlet Macaw
                )
        )
)
*/

// determine how many examples rows there will be
foreach($Categories as $family=>$sub_array)
	if(($example_count = count($sub_array['examples'])) > $example_max) // sets $example_count to the number of examples per family, if it's more than $example_max, set $example_max to $example_count
		$example_max = $example_count;

?>

<table border="1" cellpadding="5">
	<tr>
		<?php foreach($Categories as $family=>$sub_array): ?>
			<th><?php print $family; ?></th>
		<?php endforeach; ?>
	</tr>
	<tr>
		<?php foreach($Categories as $family=>$sub_array): ?>
			<th><img src="<?php print $sub_array['image']; ?>" /></th>
		<?php endforeach; ?>
	</tr>
	
	<?php for($row = 0; $row < $example_max; $row ++): ?>
	<tr>
		<?php foreach($Categories as $family=>$sub_array): ?>
		<td><?php print $sub_array['examples'][$row]; ?></td>
		<?php endforeach; ?>	
	</tr>
	<?php endfor; ?>
</table>
?>
Cheers

Re: Need help to print an array to a html table

Posted: Sat Apr 17, 2010 1:22 am
by StRoYeR
Thank you very much, you've solved a lot of some doubts that I didn't know I could have included my first doubt =)

Regards.

StRoYeR

Re: Need help to print an array to a html table

Posted: Sat Apr 17, 2010 7:22 am
by JAY6390
Hi StRoYer

I wrote this function a while back to make a table based on an associative array. Hopefully it will be of use to you

Regards

Jay