在foreach中组合多个值

时间:2014-03-07 23:28:18

标签: php foreach

我希望能够将foreach中的2个if语句组合成1个变量 这将是变量$ propertyCodeMerged。基本上,实际上会有两个if / else if条件都为真所以我希望$ propertyCode1和$ propertyCode2合并为1个变量。这必须包括重复项。我该怎么做呢? 我只为1个条件工作,但在解决多个条件时遇到问题。任何指针都会有所帮助。

$propertyCode1 = "":
$propertyCode2 = "":
$propertyCodeMerged = "";

$propGrid = @=grid;
foreach($propGrid as $property){
   $code = $property['property_code']; 
   $wo_type_id = $property['id'];
   if($code != "" && $property['complete'] == "Yes" && $property['photos'] == "Yes"){
      $propertyCode1 .= "'$code', ";
  } else if ($code != "" && $property['complete'] == "Yes" && $property['id'] == "20"){
      $propertyCode2 .= "'$code', ";
  }
}
if($propertyCodeMerged != "")
$propertyCodeMerged = substr($propertyCodeMerged, 0, -2);

实施例: 以下是@ = grid:

的示例输出
Array ( [1] => Array ( [property_code] => TESTCODE-01 [street] => 100 Fake Street 
[city] => Detroit [state] => MI [zip] => [county] => [id] => 20 [type_name_label] => Inspection 
[other_fee] => 0.00 [down_pay] => [monthly_pay] => [phone] => [resolve] => No 
[date_completed] => [photos] => Yes [report] => No [complete] => Yes [reorder] => No ) ) 

基本上,每次用户检查“完整”和“照片”复选框时,它都会记录为“是”。因此,只有标有“是”的2个复选框的属性代码/行才会被分配给$ propertyCode1。

以下是我对1条件的处理方式:

$propertyCode = "";
$propGrid = @=grid;
foreach($propGrid as $property){
   $code = $property['property_code']; 
   $wo_type_id = $property['id'];
   if($code != "" && $property['complete'] == "Yes" && $property['photos'] == "Yes"){
      $propertyCode .= "'$code', ";
  }
}
if($propertyCode != "")
$propertyCode = substr($propertyCode, 0, -2);

因此,如果有5个属性代码但只有3个标记了完整和照片复选框,则$ propertyCode应该具有如下内容:TESTCODE-01,TESTCODE-02,TESTCODE-03。 我现在想要做的是尝试包含上面的逻辑,但是当存在只有标记完整复选框且ID为“20”的属性/行时,还要添加另一个条件。

换句话说,我想将上面的1个条件示例与以下内容结合起来:

$propertyCode = "";
$propGrid = @=grid;
foreach($propGrid as $property){
   $code = $property['property_code']; 
   $wo_type_id = $property['id'];
   if($code != "" && $property['complete'] == "Yes" && $property['id'] == "20"){
      $propertyCode .= "'$code', ";
  }
}
if($propertyCode != "")
$propertyCode = substr($propertyCode, 0, -2);

1 个答案:

答案 0 :(得分:0)

$propertyCode1 = "":
$propertyCode2 = "":
$propertyCodeMerged = "";

$propGrid = @=grid;
foreach($propGrid as $property){
   $code = $property['property_code']; 
   $wo_type_id = $property['id'];
   if($code != "" && $property['complete'] == "Yes" && $property['photos'] == "Yes"){
      $propertyCode1 .= "'$code', ";
  } else if ($code != "" && $property['complete'] == "Yes" && $property['id'] == "20"){
      $propertyCode2 .= "'$code', ";
  }
}
//added this line
$propertyCodeMerged = $propertyCode1 . $propertyCode2;

if($propertyCodeMerged != "")
$propertyCodeMerged = substr($propertyCodeMerged, 0, -2);