【发布时间】:2014-07-12 03:49:38
【问题描述】:
我正在使用 PDO 查询 MySQL 数据库并根据其模型类型返回一组自行车。返回的多维数组包含各种属性(零件编号、颜色、大小等),并通过递增数字键进行索引。像这样的:
[0] => Array
(
[ItemId] => KL-5000-Y
[SeatType] => Leather
[Speed] => 5
[Model] => Killer
[Color] => Yellow
)
[1] => Array
(
[ItemId] => KL-5000-B
[SeatType] => Leather
[Speed] => 5
[Model] => Killer
[Color] => Black
)
这个数组被赋值给变量$results
然后我有一个名为 Bike 的类,它旨在将各种属性映射到受保护的变量,我可以使用公共 getter 方法在我的应用程序的其他地方访问这些变量。其中一些方法包含额外的逻辑,但这里的主要目标是在数据库结构和应用程序中其他地方的属性表示之间添加一个抽象层。
class Bike
{
private $ItemId;
private $SeatType;
private $Model;
private $Color;
public function __construct($results)
{
if(is_array($results)) {
$this->ItemId = $result[x]['ItemId'];
$this->SeatType = $result[x]['SeatType'];
$this->Model = $result[x]['Model'];
$this->Color = $result[x]['Color'];
}
}
public function getItemId()
{
return $this->ItemId;
}
public function getSeatType()
{
return $this->SeatType;
}
//etc.
我遇到的问题是:
1.) 弄清楚如何在我的 Bike 类中正确遍历数组(参见上面的“[x]”)
2.) 然后弄清楚如何正确实例化我的 html 模板中的对象
目标是创建一个表格,列出特定模型的所有属性,并按项目 ID 进行索引:
<table>
<thead>
<th>ITEM ID</th>
<th>SEAT TYPE</th>
<th>MODEL</th>
<th>COLOR</th>
</thead>
<tbody>
<?php $bike = new Bike($results); ?>
<tr>
<td><?php echo $bike->getItemId();?></td>
<td><?php echo $bike->getSeatType();?></td>
<td><?php echo $bike->getModel(); ?></td>
<td><?php echo $bike->getColor(); ?></td>
</tr>
</table>
我可以让上述内容回显一个对象,但不能回显多个对象。提前道歉。我对编程比较陌生,我认为这有一个相对简单的解决方案,但我无法弄清楚或在 SO 的其他地方找到它。
提前感谢您的帮助!
【问题讨论】:
-
您希望自己的 Bike 类返回多辆自行车的信息,还是只返回一辆 Bike?
-
多辆自行车。有 200 辆独特的自行车,我们按型号对它们进行分组,并希望在表格中显示每个型号组,突出显示它们的各种属性。