PHP foreach在foreach重复数据中而不是转义循环

时间:2013-12-04 12:52:56

标签: php foreach logic controls conditional-statements

将以下内容视为代码,

<?php
foreach ( $alldata as $alldatakey=>$alldatavalue){
 foreach ( $alldatavalue as $neededdatakey=>$neededdatavalue){

  #conditions here

  foreach (){

  if(){
    $variable = $data1;
  }

  if(){
    $variable .= $data2;
  }

  if(){
    $variable .= $data3;
  }

  }


 }
  echo $variable;
}
?>

输出:

Sewer Connected, 
Sewer Connected, Septic, 
Sewer Connected, Septic, Septic, 

Sewer Connected, 
Sewer Connected, Septic, 
Sewer Connected, Septic, Septic, 

Sewer Connected, 
Sewer Connected, Septic, 
Sewer Connected, Septic, Septic, 

Sewer Connected, 
Sewer Connected, Septic, 
Sewer Connected, Septic, Septic, 

data1,data2和data3的条件是正确的。 为什么要重复打印数据?

3 个答案:

答案 0 :(得分:1)

在此处移动您的 echo 语句

        }
        //echo $varibale;

    }
    echo $varibale;//Move here <-----

}
?>

答案 1 :(得分:0)

你需要在所有循环中写出极端

    <?php
    foreach ( $alldata as $alldatakey=>$alldatavalue){
     foreach ( $alldatavalue as $neededdatakey=>$neededdatavalue){

      #conditions here

      foreach (){

      if(){
        $varibale = $data1;
      }

      if(){
        $varibale .= $data2;
      }

      if(){
        $varibale .= $data3;
        break;
      }
      }
    if(!empty($data3)){
    break;
   }

     }
      echo $varibale;
    }
    ?>

答案 2 :(得分:0)

未公开foreach }

在回显之后放置unset($varibale);,因此您的代码看起来像这样

<?php
foreach ( $alldata as $alldatakey=>$alldatavalue) {
 foreach ( $alldatavalue as $neededdatakey=>$neededdatavalue) {
  foreach () {
    //internal loop
      if() {
           $variable = $data1;
      }
      if() {
           $variable .= $data2;
      }
      if() {
           $variable .= $data3;
      }

  }
 }
  echo $variable;
  unset($variable);  // we unset it here so that we only each out the subcat blocks for that key cat not concat all subs and primaries
}
?>