繁体   English   中英

使用函数在 PHP 中输​​出 HTML

[英]Using a function to output HTML in PHP

我试图让一个函数工作并输出变量的样式,但我无法让它们工作。

function frontstyle(){
  $worldstyle = $data[\"worldpercent\"] < \"75\" ? ' style=\"color: red;\"' : '';
  $USA        = $data[\"USApercent\"] <= \"22\" ? ' style=\"color: red;\"' : '';
}

然后在我的代码中我有

foreach ($result as $data) {
  if (strpos($_SERVER['HTTP_HOST'], 'frontpage') !== false) {
    frontstyle();
  }

我也在 foreach 之后尝试了该功能,但结果根本没有显示数据。 我的目标是在 if 语句中插入一个函数,然后如果 frontpage 显示该内联 css。

我的内联 css 块

<td width="75px" $USA><b>$ {$data["USApercent"]}</td>

如果我像这样直接在 if 语句中添加变量,这会起作用

foreach ($result as $data) {
  if (strpos($_SERVER['HTTP_HOST'], 'frontpage') !== false) {

          $worldstyle = $data[\"worldpercent\"] < \"75\" ? ' style=\"color: red;\"' : '';
          $USA  = $data[\"USApercent\"] <= \"22\" ? ' style=\"color: red;\"' : '';
 }

  echo <<<EOD
  <tr >
    <td width="120px" id="USA"><b>{$data["USApercent"]}</td>        

这是行不通的,因为$worldstyle$USA定义的内部函数frontstyle()是函数的局部范围,同样,你不喂frontstyle()$data ,所以它是undefined

即,您需要一种从函数返回值的方法,以允许if循环处理这些值,同时在foreach循环的每次迭代中将$data给函数。

您可以设想多种不同的方法来执行此操作,但一种方法是返回一个包含$worldstyle$USA的数组。 然后,您可以根据样式需要在数组中引用这些值。

即将您的功能更改为:

function frontstyle($data = [], $worldstyle = "", $USA = "", $frontstyle = [])
{
    $worldstyle = $data["worldpercent"] < 75 ? ' style=\"color: red;\"' : '';
    $USA = $data["USApercent"] <= 22 ? ' style=\"color: red;\"' : '';
    $frontstyle = ['world' => $worldstyle, 'usa' => $USA];
    return $frontstyle; // return the array with styling
}

旁注:不要对变量名使用全部大写(例如 USA),除非它们是常量

然后在您的if循环中,您可以执行以下操作:

if (strpos($_SERVER['HTTP_HOST'], 'frontpage') !== false) {
    $frontstyle = frontstyle(); // you now have access to the styling values
    $worldstyle = $frontstyle['world'];
    $USA = $frontstyle['usa'];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM