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を構築することです

情報を簡単に取得して、次のように作成できます。

$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

以下のように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 に答える