我从mysql查询中获得这个数组:
array (size=9)
0 =>
array (size=2)
'room_category' => string 'MALE GENERAL WARD' (length=17)
'vacant_beds' => string 'MG-8,MG-2,MG-4,MG-6,MG-7' (length=24)
1 =>
array (size=2)
'room_category' => string 'FEMALE GENERAL WARD' (length=19)
'vacant_beds' => string 'FG-4,FG-1,FG-2,FG-3' (length=19)
2 =>
array (size=2)
'room_category' => string 'MOTHER CHILD WARD' (length=17)
'vacant_beds' => string 'MC-2,MC-4,MC-5,MC-6' (length=19)
3 =>
array (size=2)
'room_category' => string 'TWIN' (length=4)
'vacant_beds' => string 'TW-A1,TW-A2,TW-B2,TW-C1,TW-C2' (length=29)
4 =>
array (size=2)
'room_category' => string 'NICU' (length=4)
'vacant_beds' => string 'NICU-6,NICU-1,NICU-7,NICU-3,NICU-8,NICU-4,NICU-5' (length=48)
5 =>
array (size=2)
'room_category' => string 'CLASSIC' (length=7)
'vacant_beds' => string 'CL-6,CL-8,CL-4,CL-5' (length=19)
6 =>
array (size=2)
'room_category' => string 'DELUXE' (length=6)
'vacant_beds' => string 'DLX-5,DLX-6' (length=11)
7 =>
array (size=2)
'room_category' => string 'EXECUTIVE' (length=9)
'vacant_beds' => null
8 =>
array (size=2)
'room_category' => string 'AC GENERAL WARD' (length=15)
'vacant_beds' => string 'AG-5,AG-1,AG-2,AG-3,AG-4' (length=24)现在,我想在html表中显示这个数组。我已经试过了,我只能部分地做到这一点。我希望字符串部分(即string 'MG-8,MG-2,MG-4,MG-6,MG-7' )位于单独的列中。
echo "<table>";
foreach($rows as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";我从这里得到的桌子如下所示
男性普通病房MG-8,MG-2,MG-4,MG-6,MG-7 女将军FG-4,FG-1,FG-2,FG-3 母子病房MC-2 MC-4 MC-5 MC-6 双胞胎TW-A1,TW-A2,TW-B2,TW-C1,TW-C2 NICU-6,NICU-1,NICU-7,NICU-3,NICU-8,NICU-4,NICU-5 经典的CL-6,CL-8,CL-4,CL-5 豪华DLX-5,DLX-6 执行员 通用病房AG-5,AG-1,AG-2,AG-3,AG-4
发布于 2017-01-27 20:40:42
您的逗号分隔字符串的每一项都可以通过,爆炸字符串来接收。但是,由于每个字符串可以有不同数量的元素--首先,您需要找到max元素的值。因此,您需要迭代两次$rows -首先查找元素的最大计数和第二次回显td。
echo "<table>";
$new_rows = [];
$max_count = 0;
foreach ($rows as $key => $row) {
$elements = [];
if (!empty($row['vacant_beds'])) {
$elements = explode(',', $row['vacant_beds']);
if (sizeof($elements) > $max_count) {
$max_count = sizeof($elements);
}
}
$new_rows[] = [
'name' => $row['room_category'],
'elements' => $elements,
];
}
foreach ($new_rows as $row) {
echo '<tr>';
// echo name
echo '<td>' . $row['name'] . '</td>';
// main part - items in elements we will wrap into `td`:
foreach ($row['elements'] as $e) {
echo '<td>' . $e . '</td>';
}
// if number of elements in `$row['elements']` is less
// than `$max_count` - we should add empty `<td>`
if (sizeof($row['elements']) < $max_count) {
echo str_repeat('<td></td>', $max_count - sizeof($row['elements']));
}
echo '</tr>';
}
echo "</table>";发布于 2017-01-27 20:42:53
处理所需的密钥(在您的例子中是- vacant_beds)以便进一步处理:
echo "<table border='1'>";
foreach($rows as $row) {
echo "<tr>";
foreach($row as $key => $row2){
echo "<td>" .
(($key == 'vacant_beds')? implode("</td><td>", explode(",", $row2)) : $row2)
. "</td>";
}
echo "</tr>";
}
echo "</table>";https://stackoverflow.com/questions/41902434
复制相似问题