Question

I have an array :-

$headers=array(
                        'a',
                        'b',
                        'c',
                    );

and say an object that I got from database :-

$sql = 'Select * from my_table';
$views = $DB->get_records_sql($sql);

Now my aim is to display the headers in table and display the values in the table only if the key of the field in $view in following matches $header.

    echo '<table border="1">';
    echo '<thead>';
    echo '<tr>';
    foreach($headers as $header){
        echo '<th>';
        echo $header;
        echo '</th>';
    }
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';

    foreach ($views as $view){
        echo '<tr>';
        foreach($view as $column=>$value){
            echo '<td>';
            echo $value;
            echo '</td>';
        }
        echo '</tr>';
    }

echo '</table>';

I tried using $key in place of $value and using in_array() method to check if the key of that field of $view exists in $header, but even that gives me the value rather than the name of the field. Is there any way I can check if the field name exists in array, I print out the value, else I don't.

Was it helpful?

Solution

How about the following

foreach($view as $column => $value){
    if(in_array($column, $headers)){
        echo '<td>' . $value . '</td>';
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top