我正在使用 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 的类,它旨在将各种属性映射到 protected 变量,我可以使用公共(public) 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 的其他地方找到它。
提前感谢您的帮助!
最佳答案
您的思考方式有误。您正试图将多辆自行车的属性数组变成一辆自行车,而您应该将多辆自行车属性的数组变成自行车的数组。
要将这个想法转化为代码,请将其用于您的类(class):
class Bike
{
private $ItemId;
private $SeatType;
private $Model;
private $Color;
public function __construct($result)
{
if(is_array($result)) {
// since $results is now only a single array, there is no need for [x]
$this->ItemId = $result['ItemId'];
$this->SeatType = $result['SeatType'];
$this->Model = $result['Model'];
$this->Color = $result['Color'];
}
}
public function getItemId()
{
return $this->ItemId;
}
public function getSeatType()
{
return $this->SeatType;
}
.....
所以,首先我们需要将我们的自行车放入一个数组中:
<?php
$bikes = array();
foreach ($results as $key => $attributes) {
$bikes[] = new Bike($attributes);
}
?>
然后将每辆自行车打印到您的表格中:
<table>
<thead>
<th>ITEM ID</th>
<th>SEAT TYPE</th>
<th>MODEL</th>
<th>COLOR</th>
</thead>
<tbody>
<?php foreach ($bikes as $key => $bike): ?>
<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>
<?php endforeach ?>
</table>
关于php - 将多维数组对象映射到类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23818151/