display array in two coloumns

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Jackomo0815
Forum Newbie
Posts: 1
Joined: Thu Feb 18, 2010 6:17 am

display array in two coloumns

Post by Jackomo0815 »

hi!
i've searched quite a long time but haven't found a good solution!

i receive an array for my page template which looks like
array( array(item1, content_item1), array(item2, content_item2), array(item3, content_item3), array(item4, content_item4)...)

now i'd like to show the items in a table with 2 coloumns (or more if needed, in another template)
<tr>
<td>item1</td>
<td>item2</td>
</tr>
<tr>
<td>descr1</td>
<td>descr2</td>
</tr>
....item3,4...

what do i've to do to get that work?
tried
foreach, with next in it an other things!

can anyone help me?

regards, jackomo
aravona
Forum Contributor
Posts: 347
Joined: Sat Jun 13, 2009 3:59 pm
Location: England

Re: display array in two coloumns

Post by aravona »

You could try using a while loop and a bit of coding like this (this was made for a select statement so you will need to tweak it to fit your array in)

Code: Select all

echo "<table border='1'>";    
echo "<tr><th>Item</th><th>Item Details</th></tr>";
 
while(whatever){            
 
echo "<tr><td> stuff </td><td> stuff </td></tr>";
          
}
But this will make you a table for your data to sit in. On a side note, if you get it wrong a while can loop forever, so a For loop maybe better :)
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: display array in two coloumns

Post by Weiry »

Im a little tired at the moment and the conversion of the data your receiving to a format thats printable is kinda inefficient :)
But i believe this sort of the solution your looking for.

Code: Select all

<?php
$contentArr = array( 
                array("name" => "item1", "cat" => "3", "price" => "0.12"),
                array("name" => "item2", "cat" => "5", "price" => "0.23"),
                array("name" => "item3", "cat" => "9", "price" => "0.34")
            );
$columnsArr = array();
foreach($contentArr as $item){          // There will be a better way of doing this.
    $columnsArr['header'][] = $item["name"];    // This section is inefficient as
    $columnsArr['row1'][] = $item["price"]; // you have to manually enter
    $columnsArr['row2'][] = $item["cat"];   // each row required.
}
 
print "<table>";
foreach($columnsArr as $row){
    print "<tr>";
    foreach($row as $content){
        print "<td>{$content}</td>";
    }
    print "</tr>";
}
print "</table>";
?>
Output:

Code: Select all

item1   item2   item3
0.12    0.23    0.34
3       5       9
Post Reply