这是非常多余的,我只想对所要求的任何部分以及所选择的多个部分的变化进行一次“OK OK SEND”。
if ($this->part1) return "OK TO SEND: $this->part1 ";
if ($this->part2) return "OK TO SEND: $this->part2 ";
if ($this->part3) return "OK TO SEND: $this->part3 ";
if ($this->part4) return "OK TO SEND: $this->part4 ";
if ($this->part5) return "OK TO SEND: $this->part5 ";
if ($this->part6) return "OK TO SEND: $this->part6 ";
if ($this->part7) return "OK TO SEND: $this->part7 ";
我不确定我是否只使用if和ifelse语句或循环。我确定循环最有效。任何帮助将不胜感激。
这样的东西?
$params = array($this->part1, $this->part2, $this->part3, $this->part4, $this->part5, $this->part6, $this->part7) ;
我会使用in_array函数吗?
答案 0 :(得分:1)
也许是这样的:
$params = array($this->part1, $this->part2, $this->part3, $this->part4, $this->part5, $this->part6, $this->part7);
// This will return a string noting the only option selected
function partRequested($params) {
foreach($params as $part) {
if($part) // or maybe ($part !== false) depending on what is contained
return 'OK TO SEND: ' . $part . ' ';
}
}
// This will return a single string noting all the options selected
function partsRequested($params) {
foreach($params as $part) {
if($part) // or maybe ($part !== false) depending on what is contained
$result .= 'OK TO SEND: ' . $part . ' <br />';
}
return $result;
}
partsRequested()返回的字符串如下所示:
OK TO SEND: part1
OK TO SEND: part3
OK TO SEND: part4
OK TO SEND: part5
// etc
这里有一些不同的格式
// This will return a single string noting all the options selected, different formatting
function partsRequested($params) {
foreach($params as $part) {
if($part) // or maybe ($part !== false) depending on what is contained
$result .= $part . ' <br />';
}
return $result;
}
// Then to echo the results
if($result = partsRequested($params))
echo 'OK TO SEND: ' . $result;
回显的字符串将如下所示:
OK TO SEND: part1
part3
part4
part5
答案 1 :(得分:0)
你可以这样做:
for($c = 1; $c < 8; $c++)
{
$part = "part" . $c;
if($this->$part)
return "OK TO SEND: " . $this->$part . " ";
}
我建议您使用此方法,因为您可能需要稍后添加更多部分。
编辑:如果你想要一个活跃项目数组,你可以这样做:
$active = array();
for($c = 1; $c < 8; $c++)
{
$part = "part" . $c;
if($this->$part)
$active[] = $part;
}
return $active;
-Ken