如何动态生成标题并仅在标题包含值时才打印它们?

发布于 2024-10-15 15:43:37 字数 636 浏览 0 评论 0原文

我是 PHP 新手,想知道执行以下操作的最佳方法是什么:

循环遍历 excel 文件中的一些记录并将它们输出为 HTML 表的标题,excel 中的每个标题都以标题开头,后跟索引所以你有:

Country1, Country2, Country3 ....through to Country50.

现在我正在使用以下内容,这不是很有效:

$vCountries ['country1'] = "Value of Country 1";
$vCountries ['country2'] = "Value of Country 2";
$vCountries ['country3'] = "";
$vCountries ['country4'] = "Value of Country 4";

然后我使用以下内容来检查它们是否为空然后

foreach ($vCountries as $key => $value){
if(!empty($value)){
$result  .= "<th id='$key' .$value. "</th>\n";}
}}

但它不起作用。我遗漏了这个拼图的一块。有什么想法吗?

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 table,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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哑剧 2024-10-22 15:43:37

尝试在 if 语句中添加字符串长度检查:

if (!empty($value) && strlen($value) > 0) {
    $result  .= "<th id='$key'" .$value. "</th>\n";
}

此外,“$result .=”行末尾有一个额外的右大括号,这可能会导致语法错误

至于数组的低效构建,尝试按照以下方式进行操作:

$vCountries = array();
for ($i = 1; $i <= 50; ++$i) {
    $vCountries['country' . $i] = "Value of country " . $i;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文