我在从二维数组创建表时遇到一些问题。
我从一个页面获得动态数组,如
Array
(
[0] => Array
(
[0] => 1374
[id] => 1374 )
[1] => 223
[version_id] => 223
[1] => Array
(
[0] => 1540
[id] => 1540)
[1] => 224
[version_id] => 224
[2] => Array
(
[0] => 1541
[id] => 1541)
[1] => 225
[version_id] => 225
)
我想要表格中的数据,
答案 0 :(得分:1)
by html structure
“行”<tr>
必须首先呈现“列”<td>
每行渲染会更容易
这正是你想要的......
定义样本$ data
$data = array(
array(
0 => 1374,
'id' => 1374,
1 => 223,
'version_id' => 223
),
array(
0 => 1540,
'id' => 1540,
1 => 224,
'version_id' => 224
),
array(
0 => 1541,
'id' => 1541,
1 => 225,
'version_id' => 225
)
);
假设您知道字段信息或通过mysql_field_name检索
$fields = array('id', 'version_id');
echo '<table class="spec">
<thead>
<tr>
<th>name</th>';
for ($n = 0; $n < sizeof($data); $n++) {
echo '
<th>array_data-' . $n . '</th>';
}
echo '
</tr>
</thead>
<tbody>';
for ($i = 0; $i < sizeof($fields); $i++) {
echo '<tr>
<td>' . $fields[$i] . '</td>';
foreach ($data as $row) {
echo '<td>' . $row[$i] . '</td>';
}
echo '</tr>';
}
echo '</tbody>
</table>';
答案 1 :(得分:1)
$multidim_arr = array
(
array
(
0 => 1374,
1 => 223
),
array
(
0 => 1540,
1 => 224
),
array
(
0 => 1541,
1 => 225
)
);
$n = count($multidim_arr);
$z = count($multidim_arr[$n-1]);
echo "<table>";
for($j = 0; $j<$z;$j++) {
echo "<tr>";
for($i = 0; $i<$n; $i++) {
echo "<td>".$multidim_arr[$i][$j]."</td>";
}
echo "</tr>";
}
echo "</table>";
首先在PDO中执行PDO :: FETCH_NUM而不是PDO :: FETCH_BOTH 检查http://php.net/manual/en/pdostatement.fetch.php
问候
@edit或使用键:
<?php
$multidim_arr = array
(
array
(
'id' => 1374,
'version_id' => 223
),
array
(
'id' => 1540,
'version_id' => 224
),
array
(
'id' => 1541,
'version_id' => 225
)
);
$n = count($multidim_arr);
$z = count($multidim_arr[$n-1]);
$keys = array_keys($multidim_arr[$n-1]);
echo "<table>";
for($j = 0; $j<$z;$j++) {
echo "<tr>";
for($i = 0; $i<$n; $i++) {
echo "<td>key: ".$keys[$j]." and value: ".$multidim_arr[$i][$keys[$j]]."</td>";
}
echo "</tr>";
}
echo "</table>";
@edit另一个例子
<?php
$multidim_arr = array
(
array
(
0 => 1374,
'id' => 1374,
1 => 223,
'version_id' => 223
),
array
(
0 => 1540,
'id' => 1540,
1 => 224,
'version_id' => 224
),
array
(
0 => 1541,
'id' => 1541,
1 => 225,
'version_id' => 225
)
);
$n = count($multidim_arr);
$z = count($multidim_arr[$n-1])/2;
$keys = array('id', 'version_id');
echo "<table>";
for($j = 0; $j<$z;$j++) {
echo "<tr>";
for($i = 0; $i<$n; $i++) {
echo "<td>key: ".$keys[$j]." and value: ".$multidim_arr[$i][$keys[$j]]."</td>";
}
echo "</tr>";
}
echo "</table>";
但是你必须知道钥匙。
答案 2 :(得分:0)
//尚未测试但应该很好..
$count_multi = count($multidim_arr);
echo '<table border="1"><tbody><tr>';
for($i=0;$i<$count_multi;$i++)
{
$subarr = $multidim_arr[$i];
echo '<td>Content at index'.$i.' of multi-dimensional array <br />'.$subarr['id'].'</td>';
}
echo '</tr></tbody></table>';