View Full Version : Array to html table
aka Robbie
09-15-2007, 06:35 PM
I'm trying to take an array and turn it into an html table where the number of columns can be altered. Each number appears in a seperate cell. The code I have reached is:
$input = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten');
$cols = 5;
echo "<table border=\"5\" cellpadding=\"10\">";
for ($i=0; $i < count($input); $i++)
{
echo "<tr>";
for ($c=0; $c<$cols; $c++)
{
echo "<td>$input[$i]</td>";
}
echo "</tr>";
}
echo "</table>";
But instead of it looking like:
one two three four five
six seven eight nine ten
It looks like:
one one one one one
two two two two two
three three three three three
four four four four four
five five five five five
six six six six six
seven seven seven seven seven
eight eight eight eight eight
nine nine nine nine nine
ten ten ten ten ten
Where am I going wrong?
djr33
09-15-2007, 11:56 PM
for () {
--for () {
--}
}
The inner loop is executed in its entirety each time the outer loop runs once.
So, you get one of the outer loop (ie a single number) run through the inner loop fully-- outputting an entire row of that number.
You can't do this just with two loops. You'll need a bit more math than that. But nothing too complex.
Here's the simplest solution I can think of:
$input = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten');
$cols = 5;
echo "<table border=\"5\" cellpadding=\"10\">";
for ($i=0; $i < count($input); $i++)
{
echo "<tr>";
for ($c=0; $c<$cols; $c++)
{
echo "<td>$input[$i+$c]</td>";
}
echo "</tr>";
$i += $c;
}
echo "</table>";
Note $i+$c.
There are a couple other ways as well, such as using $c%$cols, which would give the remainder of $c/$cols, which should work for you as the $c value, then just using $c value for the numbers. (Or replace $c with $i in the last sentence if that makes more sense-- you'd only have one.)
Also, though it doesn't apply so easily in this case, you should look into foreach() loops.
foreach($array as $item) {
echo $item;
}
foreach($array as $key => $item) {
echo $key.': '.$item;
}
By the way, using "$array[$item]" hasn't always worked for me, though that may be more the case with strings, like "$array['item']".
End the quotes, and use a dot to join the parts, and that will likely run smoother in at least some cases. I'm not sure about the specifics.
"something".$array[$item]."something";
<?php if(count($input)) { ?>
<table>
<?php for($i = 0; $i < count($input); ++$i) { ?>
<?php if(!$i) { ?>
<tr>
<?php } else if(!($i % 5)) { ?>
</tr>
<tr>
<?php } ?>
<td><?php echo $input[$i]; ?></td>
<?php } ?>
</tr>
</table>
<?php } ?>
aka Robbie
09-16-2007, 09:55 AM
Thanks for your replies guys.
Twey - based on your answer how would I modify it so the table appears as:
one six
two seven
three eight
four nine
five ten
djr33
09-16-2007, 10:22 AM
$i % 5... change that to the number you want, like 2.
Twey, I understand breaking out of PHP for some long chunks of code, but single lines? Eek. You have more PHP tags now than you had echo statements.
Heh, I started looking at this issue in Lisp, spent a fair while figuring it out (I'm just learning Lisp and I'm pretty bad with this kind of array arithmetic anyway), then switched back to my browser and remembered that there was actually a reason I was playing with it.
(defun splitarr (grp arr)
(apply #'mapcar
(append '(list)
(loop for j from 0 to (- grp 1) collecting
(loop for i in arr when (= j (mod i grp)) collecting i)))))
<?php
function splitarr($grp, $arr) {
$r = array();
foreach($arr as $k => $v)
$r[floor($k / $grp)][] = $v;
return $r;
}
?>
<table>
<?php foreach(splitarr(2, $input) as $row) { ?>
<tr>
<?php foreach($row as $cell) { ?>
<td><?php echo $cell; ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
aka Robbie
09-16-2007, 01:01 PM
But that appears to give me two rows instead of two columns. How do I use:
$cols = 2;
so that changing this number to 3, 4 or 5 etc will change the number of columns?
Whoops, I meant floor($k / $grp) not $k % $grp. Edited.
The first parameter passed to splitarr() is the number of elements to put in each group. Change it as you like.
Twey, I understand breaking out of PHP for some long chunks of code, but single lines? Eek. You have more PHP tags now than you had echo statements.Yes, but the output's neater (unless I filled my echoed HTML up with \ns and \ts). Personally, I'd rather use Smarty or Django's template system. A proper templating system is much neater than PHP's default intermixed code and presentation.
djr33
09-16-2007, 01:25 PM
echo '<table>
<tr>
<td>
</td>
</tr>
</table>';
//shrug
Eight spaces per level? :p
Doesn't look that much neater than mine, to me, anyway. Especially when you're outputting variables as well, and in real HTML there tend to be attributes:
echo '<table class="someclass">
<tr class="otherclass" onclick="alert(\'Hello!\');">
<td onclick='alert("Hello! How\\\'re you?");'>
' . $somevalue . '
</td>
</tr>
</table>';
// or...
echo "<table class=\"someclass\">
<tr class=\"otherclass\" onclick=\"alert('Hello!');\">
<td onclick='alert(\"Hello! How\\'re you?\");'>
$somevalue
</td>
</tr>
</table>";A heredoc block might be appropriate, but they're less efficient than breaking out of PHP parsing mode (actually, so is echo, I think, especially with the double quotes).
djr33
09-16-2007, 01:37 PM
Eight spaces per level?No, tabs.
<td onclick='alert(\"Hello! How\\'re you?\");'>The slash would escape the other slash--
<td onclick='alert(\"Hello! How\\\'re you?\");'>
Personally, I find using dots to be just fine.
echo 'something'.$var.'something';
No, tabs.Ah, vB converted them to eight spaces each.
The slash would escape the other slash--It was meant to (that was the double-quoted one, the single quote didn't need to be escaped for PHP).
Personally, I find using dots to be just fine.
echo 'something'.$var.'something';But it's still ugly (as seen in the single-quoted example) and mixes presentation with logic, which is A Bad Thing.
djr33
09-16-2007, 02:52 PM
I think it makes perfect sense.
echo $var1.'text1'.$var2.'text2';
It's not very complex logic, certainly. Could be very overwhelming if you had lots of operations in there, but just a single variable seems reasonable.
In fact, it's less to figure out than breaking out of PHP, I'd say.
As for the slash, ah, yes. But... it isn't needed, then. You either have one or three, as the two will cancel each other out, rendering the effect null.
Again, yes, for a little data on a single line (and I've done it: see the <?php echo ... ?> bit?). However, you're probably storing HTML (output/presentation data) in the logic section of the program if you find yourself doing this (or vice versa, if you have a long echo statement in the middle of a chunk of HTML).
In fact, it's less to figure out than breaking out of PHP, I'd say.Again, a template system would be preferable.
As for the slash, ah, yes. But... it isn't needed, then. You either have one or three, as the two will cancel each other out, rendering the effect null.No. A single backslash escapes the character after it, although PHP will usually just render the slash if the next character doesn't make any sense when escaped. You seem to be misunderstanding the code a little here: let's break it down a little.In our PHP code, we have two backslashes and an apostrophe: \\' When this is parsed by PHP, the first backslash escapes the second, resulting in a single literal backslash, so it becomes \' The single backslash then escapes the apostrophe for Javascript, so the final character is just a single apostrophe, '.And, it just goes to prove my point if even someone experienced with PHP can still get confused over what's escaping what :)
djr33
09-16-2007, 03:31 PM
Haha. Hmmm... I was thinking about it backwards.
However, you wouldn't need to escape the first slash in the first place there. That was my main point.
Then I got it in my head that the escaping would hurt.
However, you wouldn't need to escape the first slash in the first place there. That was my main point.Yes you would: just having \' will result in a literal apostrophe being sent to Javascript, with no backslash, and thus it would break.
/EDIT: Actually, no, it's not necessary, at least in PHP5. However, that makes it a special case (one of the guesses I mentioned above) and so even less predictable and more confusing.
djr33
09-16-2007, 04:07 PM
"a\"a", 'a\'a', 'a"a', and "a'a" are correct from my experience.
"a\'a" will output \', like 'a\"a'.
It's been my impression that escaping only applies when a certain character has a use in that type of output (1. single quote, 2. double quote, 3. heredoc)
1. just \' is needed, and \\ when you don't want to escape the ', like \\'.
2. \t, \n, \[othercharacters], \", \$, and, again, \\.
3. only \$ and \{, i'd assume. Never really played with it.
So, if you had \' in single quotes, it wouldn't escape it as there is no point in escaping that ' for php. (For javascript, yes, but not within the php parsing).
\\ escapes escaping, not a literal backslash. So it would only have an effect if it were escaping escaping, if the next character were to be parsed as something special aside from the \.
In fact, it seems like it would be very important to check this, as javascript would receive \\', and escape it itself, though that doesn't seem to be an issue. Odd.
Yes. But, that's inconsistent behaviour (as demonstrated by the fact that it took you two paragraphs to explain it :)).
djr33
09-16-2007, 04:11 PM
Did you notice my edit? I just updated the post to make more sense. Plus, something went wrong with the first post and cut off a bit. :p
I think you're trying to say that \\ isn't a literal backslash. If you are, you're wrong :)
djr33
09-16-2007, 08:47 PM
It's an escaped backslash, but I'd think that should only apply when escaping applies to the second backslash in the first place.
finedesignz
07-09-2009, 04:58 PM
Also, though it doesn't apply so easily in this case, you should look into foreach() loops.
foreach($array as $item) {
echo $item;
}
foreach($array as $key => $item) {
echo $key.': '.$item;
}
I was wondering if you might expound on using the foreach loops to create a table.
I would like to use:
foreach ($search->body->Items->Item as $object) {
echo '<td>';
echo '<a href="' . $object->DetailPageURL . '"><img src="' . $object->MediumImage->URL . '" /></a><br />';
echo '<a href="' . $object->DetailPageURL . '">' . $object->ItemAttributes->Title . '</a>';
echo '</td>';
}
I want to be able to dynamically change the number of rows and columns, but have the foreach loop through each item once.... I've tried several suggestions in this post, but am still having trouble with this.
Thanks in advance for your expert help.
Jesdisciple
07-10-2009, 04:40 AM
Please don't necromance (bring dead threads back to life). If you really need to draw attention to an old thread, link to it.
As for your question, you'll have to use the $key => $value syntax because without an iterator (the key) you can't tell which row you should be on. Having that, you can figure whether you need to start a new row with $key % $columns == 0 (which determines whether $key is a multiple of $columns).
mcanous
05-18-2011, 03:17 PM
I have this code that I am confused about, I can get the outpoot into an array but I cannot organize it into a table, please help
<META HTTP-EQUIV="REFRESH" CONTENT="20">
<?php
$xmlUrl = "https://secure.ifbyphone.com/ibp_api.php?api_key=6a9212f2af5a0ee41df847fd59eb63acf219404c&action=report.call_detail&start_date=20110517&end_date=20201231&format=csv&date_added=1&phone_label=1&dnis=1&ani=1&call_duration=1&transfer_to_number=1&call_type_filter=All"; // XML feed file/URL
$xmlStr = file_get_contents($xmlUrl);
$filearray = explode("\n", $xmlStr);
while (list($var, $val) = each($filearray)) {
++$var;
$val = trim($val);
print "Line $var: $val<br />";
$input =
$cols = 5;
echo "<table border=\"5\" cellpadding=\"10\">";
for ($i=0; $i < count($input); $i++)
{
echo "<tr>";
for ($c=0; $c<$cols; $c++)
{
echo "<td>$input[$i]</td>";
}
echo "</tr>";
}
echo "</table>";
}
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.