How to dynamically generate headings and only print them if they contain a value?
I am new to PHP and wondering what would be the best way of doing the following:
Loop through some records within an excel file and output them as headings for an HTML tabl开发者_JS百科e,each of the headings in the excel begin as a Title followed by an index so you have:
Country1, Country2, Country3 ....through to Country50.
For now I am working with the following which is not very efficient:
$vCountries ['country1'] = "Value of Country 1";
$vCountries ['country2'] = "Value of Country 2";
$vCountries ['country3'] = "";
$vCountries ['country4'] = "Value of Country 4";
then I use the following to check if they are empty then
foreach ($vCountries as $key => $value){
if(!empty($value)){
$result .= "<th id='$key' .$value. "</th>\n";}
}}
But it doesn't work. I'm missing a piece of this puzzle. Any ideas?
Try adding a string length check to the if statement:
if (!empty($value) && strlen($value) > 0) {
$result .= "<th id='$key'" .$value. "</th>\n";
}
Also, you've got an extra closing curly brace at the end of your "$result .=" line which will probably be causing a syntax error
As for the inefficient building of the array, try something along these lines:
$vCountries = array();
for ($i = 1; $i <= 50; ++$i) {
$vCountries['country' . $i] = "Value of country " . $i;
}
精彩评论