我有这个代码。我需要打印数组中的数据。问题是我设计表有2列,一列有名,第二列有计数。而且我不知道如何在两列中打印值。
class Tabel{
private $tabel = array();
public function getElemente(){
$conn = mysql_connect('localhost','root',''); /
$db_selected = mysql_select_db('world',$conn);
$result = mysql_query("SELECT c.Continent, COUNT(c.Name) FROM country c
GROUP BY c.Continent
Order By COUNT(c.Name) desc");
while($row = mysql_fetch_array($result)){
//echo $row['Continent'] . " " . $row['COUNT(c.Name)']."<br>";
$this->tabel[]=$row['Continent']. " " . $row['COUNT(c.Name)'];
}
}
public function afisare(){
print_r($this->tabel);
echo"<table border=1 cellpading=0 cellspacing=0 >";
echo"<th>Continent</th>";
echo"<th>Tari</th>";
foreach($this->tabel as $value){
echo"<tr>";
echo"<td>".$value."</td>";
echo"</tr>";
}
}
我想到矩阵..和asociative数组。我尝试了一些想法......但没有运气。语法杀了我。
答案 0 :(得分:0)
我会尝试改变一些事情:
让我们从您的SQL语句开始: 除了Continent和count之外,请选择continent-id。
在$ table变量中使用此continentId作为键。您的代码可能如下所示:
$result = mysql_query("SELECT c.ContinentId, c.Continent, COUNT(c.Name) as count FROM country c
GROUP BY c.Continent
Order By COUNT(c.Name) desc");
while($row = mysql_fetch_array($result)){
$this->tabel[$row['ContinentId']]['continent'] = $row['Continent'];
$this->tabel[$row['ContinentId']]['count'] = $row['count'];
}
注意:对于您的列“COUNT(c.Name)”,我给出了一个别名(“count”)。
使用$ table-variable中的这些新信息,您可以编辑foreach:
echo"<table border=1 cellpading=0 cellspacing=0 >";
echo"<th>Continent</th>";
echo"<th>Tari</th>";
foreach($this->tabel as $key=>$value){
echo"<tr>";
echo"<td>".$value['continent']."</td>";
echo"<td>".$value['count']."</td>";
echo"</tr>";
}
这应该为你工作。
除此之外: 如果可以,我会留意是否有任何方法可以防止来自您班级的任何数据。