2016-02-09 31 views
2

我有5段數據。將多個數據分配給循環內的var並嘗試在循環外使用var

我把所有5段數據放入while循環中的一個變量中。然後,我試圖在while循環之外使用變量 - 但是所有放入的數據仍然回顯。

目前,我可以將數據放入,併成功獲取1條數據。我想回顯所有5個數據。

代碼:

 $s = <a search query that gets data from external db> 
     while($data = $r->FetchRow($s)) { 
     $addr = 'test address'; 
     if($data['image'] == '') { $data['image'] = 'nophoto.jpg';} 
      $a = '<div style="height: 85px; width: 100%;"><img src="http://website.com/'.$data['image'].'" align="left" border="0" hspace="15" alt="Click for details" height="85px" width="120px" />'.$addr.''; 
            } 
     $m = "This is a test message <br />" . 
     $m = "".$a."" . 
     $m = "This is the end of a test message"; 
     echo $m; 

回答

0

在你的循環,你要$a分配值。

因此,最新值覆蓋舊值,因此您將獲得最後一個值。

如果你想獲得所有的數據,你需要在循環中追加$a

更正代碼:

$a = ''; 
$s = <a search query that gets data from external db> 
while($data = $r->FetchRow($s)) { 
$addr = 'test address'; 
if($data['image'] == '') { 
    $data['image'] = 'nophoto.jpg'; 
} 
$a .= '<div style="height: 85px; width: 100%;"><img src="http://website.com/'.$data['image'].'" align="left" border="0" hspace="15" alt="Click for details" height="85px" width="120px" />'.$addr.''; 
} 
$m = "This is a test message <br />" . 
$m = "".$a."" . 
$m = "This is the end of a test message"; 
echo $m; 
+0

完美的答案!謝謝你解釋。 – user3259138