php - 将每个mongodb记录输出到html表中

标签 php mongodb crud php-mongodb

我正在构建一个从 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/

相关文章:

java - 是否有一个开源工具,用于将现有数据库公开为一组 Web 服务

php - 如何计算 wp-db7 表单中特定表单帖子 id 的行数

php - 无法打开流 : HTTP request failed! HTTP/1.1 422 无法处理的实体

java - Mongodb查询匹配以空格分隔的单词

spring - 如何使用Spring Security在代码中获取用户的授权凭据?

php - 让 Gii 在 Yii 2.0 上工作

javascript - 无法从部分 View Laravel 访问 javascript

php - 如何使用对象方法作为回调函数

java - 在 Spring Data MongoDB 中处理读取超时的最佳方法

java - 使用批量数据设计独立于数据源的应用程序