Here's a simple function I wrote to display tabular data without having to input each column name:
(Also, be aware: Nested looping)
function display_data($data) {
$output = '';
foreach($data as $key => $var) {
$output .= '';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '' . $k . ' | ';
} else {
$output .= '' . $v . ' | ';
}
}
$output .= '
';
}
$output .= '
';
echo $output;
}
UPDATED FUNCTION BELOW
Hi Jack,
your function design is fine, but this function always misses the first dataset in the array. I tested that.
Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.
The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.
You can avoid that by moving the if condition above the second foreach loop like this:
function display_data($data) {
$output = "";
foreach($data as $key => $var) {
//$output .= '';
if($key===0) {
$output .= '
';
foreach($var as $col => $val) {
$output .= "" . $col . ' | ';
}
$output .= '
';
foreach($var as $col => $val) {
$output .= '' . $val . ' | ';
}
$output .= '';
}
else {
$output .= '';
foreach($var as $col => $val) {
$output .= '' . $val . ' | ';
}
$output .= '
';
}
}
$output .= '
';
echo $output;
}
Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016
and another update that removes redundant code blocks that hurt maintainability of the code.
function display_data($data) {
$output = '';
foreach($data as $key => $var) {
$output .= '';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '' . $k . ' | ';
} else {
$output .= '' . $v . ' | ';
}
}
$output .= '
';
}
$output .= '
';
echo $output;
}