PHP–在foreach循环中使用带if语句的外部函数
我是PHP新手,请温柔一点。 我需要做什么更改才能在PHP中工作PHP–在foreach循环中使用带if语句的外部函数,php,html,function,if-statement,foreach,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($dat
<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
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 ?>
一切都与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 ?>
在php中,如果在函数块中定义变量,则只能在该块中访问该变量,该变量不存在于该函数之外,或者如果在其他地方定义了该变量,则该变量可能存在,但没有在函数中为其指定的正确值。您可以在此处阅读更多:。一种方法是从typ__1返回布尔值,并将其分配给在foreach循环中定义的变量。感谢您的建议Jędrzej和链接!我来检查一下范围,没问题。玩得高兴谢谢你,这似乎有效!是啊还有一个问题:理论上,我可以把第二个if语句也放到foreach之外的函数中吗?比如:同样,您需要将参数添加到衣服函数中。然后您可以返回或回显$bottom。