I’m building an app which pulls records from a MongoDB. I’ve built the thead>tr>th as follows:
// 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>";
}
This gives me:
<thead>
<tr>
<th>name</th>
<th>address</th>
<th>city</th>
</tr>
</thead>
This works very well, it grabs all the keys and builds the table head. I don’t have to specify anything and the thead is built dynamically from the data. The part I’m unable to figure out is building all of the tr>td’s
I can easily grab the info and build it like this:
$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>";
}
Doing so requires me to modify my php every time I add a new field. How can I build the tr>td’s automagically based on the data from mongodb like I am with the thead?
My data looks like this:
{
"name": "Some Venue",
"address": "1234 Anywhere Dr.",
"city": "Some City"
}
Have you try to use second foreach as below