2014-11-14 104 views
1

抱歉,如果標題是不明確的,但我需要的是這樣的:店數組變量裏面的foreach

我有一個分貝一個foreach打印數據和我有應存儲陣列,然後多個變量用所有其他變量打印主變量。

foreach ($aItems as $i => $aItemInfo) { 

    $var1 = ''; 
    $var2 = ''; 
    $var3 = ''; 
    $var1 .= $aItemInfo['val1']; 
    $var2 .= $aItemInfo['val2']; 
    $var3 .= $aItemInfo['val3']; 

    // some operations with the db data 
    if ($var1 > 0) { 

     if ($var1 == 1 && $var2 == 0) { 
      $a = 'Some text.'; 
     } 
     else if ($var1 == 1 && $var2 == 1) { 
      $a = 'Some other text.'; 
     } 
     else if ($var1 > 1 && $var2 == 0) { 
      $a = 'Some new text.'; 
     } 
     else if ($var1 > 1 && $var2 == 1) { 
      $a = 'Some other new text.'; 
     } 

     $new_var = ''; 
     // html code 
     $new_var .= '<div id=""> 
         <a id="">' . $othervar . '</a> 
        </div> 
        <div id=""> 
         <span id="">' . $a . '</span> 
        </div>'; 
    } 

    if ($var > 0) { 
     // html code 
     $other_var .= ' . $vars . '; 
    } 

    // html structure 
    $main_var .= ''; 
} 

和打印的主要變量:

<div class=""> 
    <?php echo $main_var; ?> 
</div> 

其實有些變量是比以前相同。我試着在「=」之前放置一個點,但我真的不知道這是如何工作或是什麼...

我在做什麼錯了?使每個變量的正確方法是什麼,以便它們可以存儲數組的每個值?

回答

1

在這種情況下,您沒有正確使用.=並置,這隻會混淆那些如果條件你做了什麼。

初始:

$var1 = '1'; 
if($var == 1) { // okay condition 

} 

第二次迭代,循環內再次另一聲明。它不會給你帶來indend做什麼:

只需創建這樣的事情:

$main_var = $new_var = ''; // initialize output outtop 
foreach ($aItems as $i => $aItemInfo) { 

    if ($aItemInfo['val1'] == 1 && $aItemInfo['val2'] == 0) { 
     $a = 'Some text.'; 
    } 
    else if ($aItemInfo['val1'] == 1 && $aItemInfo['val2'] == 1) { 
     $a = 'Some other text.'; 
    } 

    // html code 
    $new_var .= ' 
     <div id=""> 
      <a id="">' . $othervar . '</a> 
     </div> 
     <div id=""> 
      <span id="">' . $a . '</span> 
     </div> 
    '; 


    if ($aItemInfo['val1'] > 0) { 
     // html code 
     // another process here whatever it is 
    } 

    // html structure 
    $main_var .= $new_var; 
} 
+0

謝謝!現在我看到了我的錯誤。請upvote我,所以我沒有-1 :( –

+0

@ChazyChaz很高興這個幫助 – Ghost

1

試試這個:

$var1 = $aItemInfo['val1']; 
$var2 = $aItemInfo['val2']; 
$var3 = $aItemInfo['val3']; 

if ($var1 == 1 && $var2 == 0) { 
    $a = 'Some text.'; 
} 
else if ($var1 == 1 && $var2 == 1) { 
    $a = 'Some other text.'; 
} 
else if ($var1 > 1 && $var2 == 0) { 
    $a = 'Some new text.'; 
} 
else if ($var1 > 1 && $var2 == 1) { 
    $a = 'Some other new text.'; 
} 

if ($var > 0) { 
    $new_var = ''; 
    // html code 
    $new_var .= '<div id=""> 
        <a id="">' . $othervar . '</a> 
       </div> 
       <div id=""> 
        <span id="">' . $a . '</span> 
       </div>'; 
}