PHP –在foreach循环中的if语句中使用外部函数

时间:2018-09-07 11:38:10

标签: php html function if-statement foreach

我是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循环。

(这是一个简化的示例,所以那里可能有错字。)

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

一切都与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

答案 1 :(得分:1)

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

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