显示阵列作为一个表(PHP) [英] Display Array as a Table (PHP)
问题描述
我想打印使用PHP / HTML表。存储阵列内的数据是这样的:
I am trying to print a table using PHP/HTML. Data stored inside array like this:
Array ( [id] => 1 [first_name] => mike [last_name] => lastname )
我的code是如下。它运行且没有错误但并不如预期的输出。下面是PHP / HTML code:
My code is as follow. It runs and there are no error however the output is not as expected. Here is the PHP/HTML code:
<table>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<?php foreach ($res as $item): ?>
<tr>
<td><?php echo $item['id'] ?></td>
<td><?php echo $item['first_name'] ?></td>
<td><?php echo $item['last_name'] ?></td>
</tr>
<?php endforeach; ?>
</table>
结果我得到的是项目的第一个字符:
The result I get is the first character of the items:
1 2 3
1 1 1
m m m
l l l
不知道我做错了吗?我真的AP preciate的解释。
Not sure what I am doing wrong? I would really appreciate an explanation.
更新:
PHP code有没有错误:
PHP CODE that has no errors:
<?php
foreach ($result as $row)
{
echo '<tr>';
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['first_name'] . '</td>';
echo '<td>' . $row['last_name'] . '</td>';
echo '</tr>';
}
?>
这是我的数组在它只有一个行:
And this is my array with only one "row" in it:
$的输出结果变量使用的print_r($结果)裹以&lt; pre>标签
Output of $result variable using print_r($result) wrapped with < PRE > tags
Array
(
[id] => 3
[first_name] => Jim
[last_name] => Dude
)
下面是我得到的结果:
实际的表结果是:
ID First Name Last Name
3 3 3
J J J
D D D
但是,如果我在阵列有0或1名以上(即2个或更多),它完美的作品。它只是不工作时,我只有一个行元素中数组。例如这个数组,完美的作品:
However if I have 0 in array or more than 1 (meaning 2 or more) it works perfectly. IT JUST DOES NOT WORK WHEN I HAVE ONLY ONE "ROW" OF ELEMENTS INSIDE ARRAY. For example this array, works perfectly:
Array
(
[0] => Array
(
[id] => 3
[first_name] => Jim
[last_name] => Dude
)
[1] => Array
(
[id] => 4
[first_name] => John
[last_name] => Dude2
)
)
我得到这样的结果:
I get this result:
ID First Name Last Name
3 Jim Dude
4 John Dude2
我真的不知道我在做什么错。这个想法是不知道有多少项目是在表中读入$ result变量,然后使用这个变量打印HTML表格中的所有元素。表可以包含O单元,1行元素,元素的1个或多个行。
I am not really sure what I am doing wrong. The idea is not knowing how many items is in a Table read it into $result variable and then using this variable print all elements inside HTML table. Table could contain O elements, 1 row of elements, 1 or more rows of elements.
推荐答案
不要删除您的foreach循环。没有看到你的code其中你建立你的阵列,我的猜测是,你这样做是:
Do not remove your foreach loop. Without seeing your code where you build your array, my guess would be you are doing this:
$res = array('id' => 1, 'first_name'=>'mike', 'last_name'=>'lastname');
的时候,其实你可能想要做什么是这样的:
when in fact what you probably want to be doing is this:
$res[] = array('id' => 1, 'first_name'=>'mike', 'last_name'=>'lastname');
括号[]添加的所有值的数组阵列。这样,您就可以通过为每一个值的集合,而不是单个值循环。
the brackets [ ] add an array of all the values to your array. This way you can loop through each as a collection of values, not individual values.
这篇关于显示阵列作为一个表(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!