从获取的数据查询数组中动态使用列名

I have an array with fetched data from a database query:

Array
(
    [0] => stdClass Object
        (
            [dataid] => 925977
            [camp_id] => 2003001
            [cid] => 
            [userid] => ushio12
            [ip_client] => 36.74.213.75
            [register_time] => 2015-04-01 22:39:04
            [country] => Indonesia
            [game_name] => TOUCH
            [server] => SALSA
            [nominal] => Rp 100000
            [logintime] => 2015-04-01 22:39:12
        )
    //...    
    [2] => stdClass Object
        (
            [dataid] => 929703
            [camp_id] => 2003001
            [cid] => 
            [userid] => fiqri179
            [ip_client] => 125.162.70.16
            [register_time] => 2015-04-02 23:40:23
            [country] => Indonesia
            [game_name] => TOUCH
            [server] => K-POP
            [nominal] => Rp 100000
            [logintime] => 2015-04-02 23:40:26
        )

)

So far, based on the array result above, I fetch the data in view manually like this:

<tr>
    <th>dataid</td>
    <th>camp_id</td>
    <th>cid</td>
    <th>ip_client</td>
    <th>register_time</td>
    <th>country</td>
    <th>game_name</th>
    <th>server</th>
</tr>

<?php
if(isset($result))
    {
        foreach ($result as $row)
            {
                echo "<tr>"; 
                echo "<td>".$row->dataid."</td>";  
                echo "<td>".$row->camp_id."</td>";  
                echo "<td>".$row->cid."</td>";  
                echo "<td>".$row->ip_client."</td>";  
                echo "<td>".$row->register_time."</td>";  
                echo "<td>".$row->country."</td>";  
                echo "<td>".$row->game_name."</td>";  
                echo "<td>".$row->server."</td>";  
                echo "</tr>"; 
            }
    }
?>

It is because I know what info the user will search.

However, this time, I don't know what the user will search (Which columns gets returned). They may search only some specific info or whole info, so that the array result will have less or other columns that this one now.

So my question is, how to automatically generate the view based on the keys (column names) array the user try to search, so that the <th>".$key."</th> will be dynamic?

This should work for you:

Here I just cast the first stdClass in the array with index 0 to an array, that then I can grab all keys with array_keys().

<?php

    $columns = array_keys((array)$result[0]);

    echo "<tr>";
    foreach($columns as $column)
        echo "<th>$column</th>";
    echo "</tr>";

?>

EDIT:

With the rows you do the same like this:

foreach ($result as $row) {
    echo "<tr>"; 
    foreach($columns as $column)
        echo "<td>" . $row->$column . "</td>";
    echo "</tr>"; 
}