2

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

这工作得很好,它抓住了所有的钥匙并建立了表头。我不必指定任何内容,并且该广告是根据数据动态构建的。我无法弄清楚的部分是构建所有 tr>td's

我可以轻松地获取信息并像这样构建它:

$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"
}
4

1 回答 1

2

您是否尝试如下使用第二个 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>";
    }
于 2012-10-28T11:08:08.147 回答