【发布时间】:2015-10-23 08:38:20
【问题描述】:
问题是: 编写一个继承自 PHP 的 ArrayObject 类的 PHP 类。为您的新类提供一个名为 displayAsTable() 的公共函数,该函数将所有设置的键和值输出为 HTML 表。实例化该类的一个实例,为对象设置一些键,然后调用对象的 displayAsTable() 函数将您的数据显示为 HTML 表格。
我的答案是:
<?php
class View
{
//definition
private $id;
private $name;
private $email;
/*
* Constructor
*/
public function __construct($id, $name, $email)
{
$this->id = $id;
$this->name = $name;
$this->email = $email;
}
/*
* get ID
*/
public function getId()
{
return $this->id;
}
/*
* get Name
*/
public function getName()
{
return $this->name;
}
/*
* get Email
*/
public function getEmail()
{
return $this->email;
}
}
// New View List Class which extends arrayObject in PHP
class ViewList extends ArrayObject
{
/*
* a public function to return data
*/
public function displayAsTable() // or you could even override the __toString if you want.
{
$sOutput = '<table border="1"><tbody>';
foreach ($this AS $user)
{
$sOutput .= sprintf('<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
$user->getId(),
$user->getName(),
$user->getEmail()
);
}
$sOutput .= print '</tbody></table>';
return $sOutput;
}
/*
* return data to string
*/
public function __toString()
{
return $this->displayAsTable();
}
}
/*
* data(s)
*/
$data = new ViewList();
$data[] = new View(1, 'Selim Reza', 'me@selimreza.com');
$data[] = new View(2, 'Half Way', 'selimppc@gmail.com');
/*
* final output
*/
print $data;
但我认为我在 2D 和 3D 数组中缺少一些用于打印的内容。 请帮助我如何以 html 格式(在表格中)打印 2D 和 3D。提前致谢。
【问题讨论】:
-
你认为你错过了什么?你为什么不确定?这个 2D、3D 是关于什么的?
-
首先考虑一下如果您有一个 3D 数组,表格应该是什么样子。把它写在纸上举几个例子,看看你的想法是否有效。然后开始编码。或者,如果您已经这样做了,请给我们一个例子。
-
@MikeSW :: 我正在考虑数组数据的数组。
-
@SBH :: 数组或数组数据的数组应在 html 中以表格形式查看。如果你运行我的代码,你会看到这个例子。我把它作为基本的。现在我需要一些更动态的 2D 或 3D
-
我认为你的问题是不理解 2D 和 3D 数组。我不认为这是一个 OOP 问题。