我有阵列:
$array = [
'category1' => [
'product33',
'product41'
],
'category2' => [
'product1',
'product45'
],
'category3' => [
'product65',
'product23',
'product423'
],
];
如何从表格中自上而下显示此数据?
这看起来应该是这样的:
category1 | category 2 | category3
product33 | product1 | product65
product41 | product45 | product23
| | product423
我试过了:
<table>
<tr>
<?php foreach ($array as $category): ?>
<td><?php echo $category ?></td>
<?php endforeach ?>
</tr>
//????
</table>
答案 0 :(得分:1)
看看这个简单的例子:
<?php
$data = [
'category1' => [
'product33',
'product41'
],
'category2' => [
'product1',
'product45'
],
'category3' => [
'product65',
'product23',
'product423'
],
];
$maxSize = 0;
foreach ($data as $category) {
$maxSize = max($maxSize, count($category));
}
for ($i=-1; $i<$maxSize; $i++) {
foreach ($data as $key=>$category) {
if (-1 === $i) {
echo $key . "\t";
} else {
echo isset($category[$i]) ? $category[$i] . "\t" : "\t\t";
}
}
echo "\n";
}
该代码的输出是:
category1 category2 category3
product33 product1 product65
product41 product45 product23
product423
注意:这应该在CLI上用于演示目的。额外的html标记只会使代码演示膨胀。
答案 1 :(得分:0)
您可以尝试这样的事情:
<?php
foreach ($array as $category)
{
echo "<td>" . key($array) . "</td>";
foreach ($category as $item)
{
echo "<td>" . $item . "</td>";
}
next($array);
}
?>
答案 2 :(得分:0)
我认为您的问题与this
非常相似首先计算$max_products
。然后打印标题(category1,category2等)。然后在行中的嵌套循环打印元素中$max_products
(您需要检查该类别是否具有索引$i
ofc的元素。)
$max_products = 0;
foreach($array as $category => $products){
$current = count($products);
if($current > $max_products){
$max_products = $current;
}
}?>
<table>
<thead>
<tr>
<?php
foreach( $array as $category => $products ){
echo "<th>$category</th>";
}
?>
</tr>
</thead>
<tbody>
<?php for( $i = 0; $i < $max_products; $i++ ){ ?>
<tr>
<?php
foreach( $array as $category => $products ){
if( $products[$i] ){
echo "<td>$products[$i]</td>";
} else {
echo "<td> </td>";
}
}
?>
</tr>
<?php } ?>
</tbody>
</table>