2017-02-27 53 views
0

我有這樣的代碼,以從文件創建我的數組:過濾陣列結果在每個循環

  <?php 
      $servers = array(); 
      $handle = @fopen("data/data.txt", "r"); 

      if ($handle) { 
       while (($buffer = fgets($handle)) !== false) { 
        $line = explode("|", $buffer); 
        $servers[] = array(
         "name" => $line[0], 
         "ip" => $line[1], 
         "type" => $line[2], 
        ); 
       } 

       fclose($handle); 
      } 
      ?> 

然後我有這樣的代碼來顯示陣列:

    <?php   
       foreach ($servers as $name => $servers): ?> 
          <td style="width:340px;">&nbsp;<?php echo $servers['name']; ?></td> 
          <td style="width:240px;"><?php echo $servers['ip']; ?></td> 
         </tr> 
       <?php endforeach; ?> 

這是陣列樣品:

Array(
[0] => Array 
    (
     [name] => aaa 
     [ip] => 123 
     [type] => good 
    ) 

[1] => Array 
    (
     [name] => bbb 
     [ip] => 345 
     [type] => good 
    ) 
) 

假設我需要過濾的結果與陣列型好, 即時通訊,試圖這個代碼,但它只返回最後一個數組:

    <?php   
       foreach ($servers as $name => $servers): ?> 
        <?php if($servers['type']=="good"){?> 
          <td style="width:340px;">&nbsp;<?php echo $servers['name']; ?></td> 
          <td style="width:240px;"><?php echo $servers['ip']; ?></td> 
         </tr> 
        <?php } ?> 
       <?php endforeach; ?> 

回答

0

的錯誤是在foreach循環變量名(使用$服務器,而不是$作爲$服務器已經存在,並且包含您的數據)

<?php foreach ($servers a $server): ?> 
      <?php if($server['type']=="good"){?> 
       <tr> 
        <td style="width:340px;">&nbsp;<?php echo $server['name']; ?></td> 
        <td style="width:240px;"><?php echo $server['ip']; ?></td> 
       </tr> 
      <?php } ?> 
    <?php endforeach; ?> 

編輯1個

過濾器陣列,然後打印

<?php 
    //Filter the array 
    $goodValues = array_filter($servers, function($e){ 
     return $e['type'] == "good"; 
     //Use this to be sure 
     //return strtolower($e['type']) == "good"; 
    }); 

    //Print the values 
    foreach ($goodValues as $value): ?> 
     <tr> 
      <td style="width:340px;">&nbsp;<?php echo $value['name']; ?></td> 
      <td style="width:240px;"><?php echo $value['ip']; ?></td> 
     </tr> 
    <?php endforeach; ?> 
+0

我嘗試過,但沒有什麼結果 – Ryewell

+0

改變,你會發布完整的HTML表,我想你錯過了一個標籤'tr'或'td' –

+0

我也嘗試沒有HTML tags..still相同的輸出 – Ryewell

0

由於這僅僅是一個numaric你不需要使用as $key => $value,只有as $value就足夠了。另請注意不同的變量名稱。

<?php foreach ($servers as $server): ?> 
    <?php if($server['type']=="good"){?> 
     <tr> 
      <td style="width:340px;">&nbsp;<?php echo $server['name']; ?></td> 
      <td style="width:240px;"><?php echo $server['ip']; ?></td> 
     </tr> 
    <?php } ?> 
<?php endforeach; ?> 
+0

我試過了,但仍然輸出..只返回最後一個數組 – Ryewell