我试图在PHP中逐行呼应一个多维数组的表格。 我有以下数组。
Array (
[0] => Array (
[0] => Paracetamol
[1] => Caffeine
[2] => Pase
)
[1] => Array (
[0] => 12
[1] => 10
[2] => 1
)
[2] => Array (
[0] => Packets
[1] => Cartons
[2] => Containers
)
)
这是我尝试foreach解决之前与此主题相关的问题时得到的输出。https:/jsfiddle.netfraqy9121 而这是我想达到的目的。https:/jsfiddle.net5akgjtvf3
<?php
$array = Array (
Array (
'Paracetamol',
'Caffeine',
'Pase'
),
Array (
12,
10,
1
),
Array (
'Packets',
'Cartons',
'Containers'
)
);
function combine($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$array = combine($array);
?>
<table border="1">
<tr>
<th>Product_name</th>
<th>Product_quantity</th>
<th>Product_size</th>
</tr>
<?php foreach($array as $row): ?>
<tr>
<td><?=$row[0]?></td>
<td><?=$row[2]?></td>
<td><?=$row[1]?></td>
</tr>
<?php endforeach ?>
</table>
试着将数组转置
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
或
function transpose($array) {
return array_map(null, ...$array);
}
这里有一些东西,会给你做任务的想法。
<?php
$meds = Array (
[0] => Array (
[0] => Paracetamol
[1] => Caffeine
[2] => Pase
)
[1] => Array (
[0] => 12
[1] => 10
[2] => 1
)
[2] => Array (
[0] => Packets
[1] => Cartons
[2] => Containers
)
);
echo "<table>";
foreach($meds as $itemz) {
echo "<tr>";
foreach ($itemz as $item) {
echo "<td>".$item."</td>";
}
echo "</tr>";
echo "<br >";
}
echo "</table>";
?>
其实有很多方法,我给其中之一
<?php
$myArray = Array (
Array (
'Paracetamol',
'Caffeine',
'Pase'
),
Array (
12,
10,
1
),
Array (
'Packets',
'Cartons',
'Containers'
)
);
$tableData = '';
foreach ($myArray as $datas){
$tableData .= '<tr>';
foreach ($datas as $data){
$tableData .= '<td>';
$tableData .= $data;
$tableData .= '</td>';
}
$tableData .= '</tr>';
}
?>
<table border="1">
<?php
echo $tableData;
?>
</table>