将每个mongodb记录输出到html表

时间:2012-10-28 10:58:52

标签: php mongodb crud mongodb-php

我正在构建一个从MongoDB中提取记录的应用程序。我已经构建了thead> tr>如下:

    // 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&gt; 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。如何基于来自mongodb的数据自动构建tr&gt; td?就像我和thead一样?

我的数据如下:

{
  "name": "Some Venue",
  "address": "1234 Anywhere Dr.",
  "city": "Some City"
}

1 个答案:

答案 0 :(得分:1)

您是否尝试使用下面的第二个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>";
    }