我正在构建一个从 MongoDB 中提取记录的应用程序。我构建了 thead>tr>th 如下:
// building table head with keys
$cursor = $collection->find();
$array = iterator_to_array($cursor);
$keys = array();
foreach ($array as $k => $v) {
foreach ($v as $a => $b) {
$keys[] = $a;
}
}
$keys = array_values(array_unique($keys));
// assuming first key is MongoID so skipping it
foreach (array_slice($keys,1) as $key => $value) {
echo "<th>" . $value . "</th>";
}
这给了我:
<thead>
<tr>
<th>name</th>
<th>address</th>
<th>city</th>
</tr>
</thead>
这工作得很好,它捕获所有的键并构建表头。我不必指定任何内容,并且 thead 是根据数据动态构建的。我无法弄清楚的部分是构建所有 tr>td
我可以轻松获取信息并像这样构建它:
$cursor = $collection->find();
$cursor_count = $cursor->count();
foreach ($cursor as $venue) {
echo "<tr>";
echo "<td>" . $venue['name'] . "</td>";
echo "<td>" . $venue['address'] . "</td>";
echo "<td>" . $venue['city'] . "</td>";
echo "</tr>";
}
这样做需要我每次添加新字段时都修改我的 php。如何像使用 thead 一样根据 mongodb 的数据自动构建 tr>td?
我的数据如下所示:
{
"name": "Some Venue",
"address": "1234 Anywhere Dr.",
"city": "Some City"
}
最佳答案
您是否尝试使用如下所示的第二个 foreach
$cursor = $collection->find();
$cursor_count = $cursor->count();
foreach ($cursor as $venue) {
echo "<tr>";
foreach (array_slice($keys,1) as $key => $value) {
echo "<td>" . $venue[$value] . "</td>";
}
echo "</tr>";
}
关于php - 将每个mongodb记录输出到html表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108234/