2016-02-09 33 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