-1

这是非常多余的,我只想对请求的任何部分以及正在选择的多个部分的任何变化说一次“OK TO 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 函数吗?

4

2 回答 2

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
于 2013-06-17T18:40:11.757 回答
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;

-肯

于 2013-06-17T18:25:54.807 回答