【问题标题】:PHP – use outside function with if-statements inside foreach-loop [duplicate]PHP – 在 foreach 循环中使用带有 if 语句的外部函数 [重复]
【发布时间】:2019-02-12 18:19:22
【问题描述】:

我是 PHP 新手,请轻点。 我需要更改什么才能在 PHP 中进行这项工作?

 <div>some HTML here</div>

 <?php
   function typ__1() {
     if ($temperature >= 29) {
       $hot = true;
     } else {
       $hot = false;
     }
   }
 ?>

 <?php foreach (array_slice($data->something->something, 0, 5) as $day):
     $temperature = $day->temperature;
     typ__1();
     if ($hot == true) {
       $bottom = "Shorts";
     } else if ($hot == false) {
       $bottom = "Pants";
     }
     <div><?php echo $bottom ?></div>
 <?php endforeach ?>

所以主要问题/问题是我是否正确使用了该功能。我可以在外部函数中编写 if 语句,然后在内部函数中使用它们吗? foreach 循环?原因/目标是缩短 foreach 循环。

(这是一个简化的示例,因此其中可能存在拼写错误。)

感谢您的帮助!

【问题讨论】:

  • 在php中如果你在一个函数块中定义一个变量,你只能在那个家伙中访问这个变量,该变量不存在于该函数之外(或者如果它被定义在其他地方可能存在,但没有您在函数中分配给它的正确值)。您可以在这里阅读更多内容:php.net/manual/en/language.variables.scope.php。一种方法是从 typ__1() 返回布尔值,并将其分配给您在 foreach 循环中定义的变量。

标签: php html function if-statement foreach


【解决方案1】:

一切都与 PHP 变量的范围有关。您应该像这样将变量“注入”到函数中:

<div>some HTML here</div>

 <?php
   function typ__1($temperature) {
     if ($temperature >= 29) {
       return  true;
     }

     return false;

   }
 ?>

 <?php foreach (array_slice($data->something->something, 0, 5) as $day):
     if (typ__1($day->temperature)) {
       $bottom = "Shorts";
     } else if (typ__1($day->temperature)) {
       $bottom = "Pants";
     }
     <div><?php echo $bottom ?></div>
 <?php endforeach ?>

http://php.net/manual/en/language.variables.scope.php

【讨论】:

  • 感谢您的建议 Jędrzej 并感谢您提供链接!我会检查范围。
  • 没问题。玩得开心;)
【解决方案2】:

在你的函数中添加参数并返回一个值。

<?php
   function typ__1($temperature) {
     if ($temperature >= 29) {
       $hot = true;
     } else {
       $hot = false;
     }
     return $hot;
   }
 ?>

 <?php foreach (array_slice($data->something->something, 0, 5) as $day):
     $temperature = $day->temperature;
     $hot=typ__1($temperature);
     if ($hot == true) {
       $bottom = "Shorts";
     } else if ($hot == false) {
       $bottom = "Pants";
     }
     <div><?php echo $bottom ?></div>
 <?php endforeach ?>

【讨论】:

  • 感谢 Atal,这似乎有效!是的! :D 另一个问题:理论上我是否也可以将第二个 if 语句也放入 foreach 之外的函数中?喜欢:&lt;?php function typ__1($temperature){} ?&gt; &lt;?php function clothes() { if ($hot == true) { $bottom = "Shorts"; } else if ($hot == false) { $bottom = "Pants"; } ?&gt; &lt;?php foreach (array_slice($data-&gt;something-&gt;something, 0, 5) as $day): $temperature = $day-&gt;temperature; $hot=typ__1($temperature); clothes(); &lt;div&gt;&lt;?php echo $bottom ?&gt;&lt;/div&gt; &lt;?php endforeach ?&gt;
  • 再次,您需要将参数添加到您的 clothes() 函数。然后你可以返回或回显$bottom
猜你喜欢
  • 1970-01-01
  • 2012-06-22
  • 2017-01-13
  • 2019-12-12
  • 2021-02-04
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 1970-01-01
相关资源
最近更新 更多