我应该使用数组还是对象
Should I use Array or Objects
首先我会说,是的,我搜索过这个...我正在阅读有关编程的书籍以增加我的知识。目前我还没有找到这个问题的答案。我的应用程序有一个可行的解决方案,但它看起来一团糟。这是 PHP.
情况:我正在创建一个应用程序,其中包含从数据库中的 3 个表中提取的动态菜单(食物):
menu_types:
id name
1 Bar
2 Kitchen
menu_categories:
id name type_id
1 Salads 2
2 Teas 1
3 Pastries 2
menu_items
id name cat_id description price image
1 Caesar 1 'hail Caesar' .00 'image location'
2 Greek 1 'Plato's fav' .00 'image location'
3 Cinnamon Roll 3 'lots-o-sugar' .50 'image location'
还有更多数据,但我想您已经明白了表格中的意思。
我的菜单看起来像这样:
(HTML 页)
茶、沙拉和糕点将是单击时仅显示其项目的链接。下面是一个粗略的例子,假设沙拉是当前页面。
**Bar** 'Caesar image', Caesar, hail Caesar, .00
Teas 'Greek image', Greek, Plato's fav, .00
**Kitchen**
Salads
Pastries
目前我将这一切合二为一class。一个对象。我最终构建了三个数组
$this->types = array(
[0] => array(
'id' => 1,
'name' => 'Bar'
),
[1] => array(
'id' => 2,
'name' => 'Kitchen'
)
);
$this->categories = array(
[Bar] => array(
'id' => 2,
'name' => 'Teas',
'type_id' => 1
)
),
[Kitchen] => array(
'id' => 1,
'name' => 'Salads',
'type_id' => 2
),
array(
'id' => 3,
'name' => 'Patries',
'type_id' => 2
)
);
$this->items 有自己的数组,$this->category[id] 是主键。
虽然这一切都变得非常混乱。尝试针对菜单的不同部分遍历这些数组是很糟糕的。我没有包括代码,因为我觉得整个思考过程从根本上是错误的。我不是在找人给我一个完整的代码示例,只是帮助我思考过程。我认为这是编码中最难的部分,思考问题的解决方案。
总而言之,我希望创建一个动态菜单,该菜单既可以根据类别过滤项目,也可以根据类型过滤类别
为了好玩,这是我使用的代码:
menu.php
<?php
class menu{
private $category;
private $size;
private $types;
private $categories;
private $items = array();
public function __construct(){
$this->setTypes();
$this->setCategories();
$this->setItems();
}
private function setTypes(){
$sql = "SELECT * FROM bbc_menu_types";
$this->types = db::rowAsAssocArray($sql);
}
public function getTypes(){
return $this->types;
}
private function setCategories(){
for ($i = 0; $i < count($this->types); $i++){
$typeId = $this->types[$i]['id'];
$sql = "SELECT * FROM bbc_menu_categories WHERE type_id = $typeId";
$this->categories[$this->types[$i]['name']] = db::rowAsAssocArray($sql);
}
}
public function getCategories(){
return $this->categories;
}
public function setItems(){
foreach ($this->categories as $key => $value){
for ($i = 0; $i < count($value); $i++){
$catId = $value[$i]['id'] . '<br />';
settype($catId, 'integer');
$sql = "SELECT * FROM bbc_menu_items WHERE category_id = $catId";
$this->items[$this->categories[$key][$i]['name']] = db::rowAsAssocArray($sql);
}
}
}
public function getItems(){
return $this->items;
}
}
?>
db.pgp(摘录)
public static function rowAsAssocArray($sql){
try{
//do not touch
$data=null;
$stmt = self::$link->prepare($sql);
$stmt->execute();
while ($result = $stmt->fetchAll(PDO::FETCH_ASSOC)){
foreach ($result as $key => $value){
$data[] = $value;
}
}
return $data;
}
catch (PDOException $e){
print $e->getMessage();
}
}
html(专家)
<?php
$i=0;
foreach ($types as $value){
echo "<li><h3>" . $types[$i]['name'] . "</h3></li>";
$i2 = 0;
while ($i2 <count($categories[$types[$i]['name']])){
if ($_GET['cat'] === strtolower($categories[$types[$i]['name']][$i2]['name'])){
echo "<li class='active'><a href='?rt=menu&cat=";
} else {
echo "<li><a href='?rt=menu&cat=";
}
echo strtolower($categories[$types[$i]['name']][$i2]['name']) . "'>" . $categories[$types[$i]['name']][$i2]['name'] . "</a></li>";
$i2++;
}
$i++;
}
?>
</ul>
</nav>
</div><!-- end menu-links -->
</div><!-- end col -->
<div class="col-sm-12 col-md-9">
<div class="menu-links-big">
<?php
$i = 0;
while ($i < count($items[ucfirst($_GET['cat'])])){
?>
<div class="menu-item">
<img src="<?php echo $items[ucfirst($_GET['cat'])][$i]['image']; ?>" alt="" class="img-thumbnail shadow alignleft">
<h3><?php echo $items[ucfirst($_GET['cat'])][$i]['name']; ?></h3>
<p><?php echo $items[ucfirst($_GET['cat'])][$i]['description']; ?></p>
<div class="price"><?php echo '$' . $items[ucfirst($_GET['cat'])][$i]['price']; ?></div>
</div><!-- end item -->
<?php
$i++;
}
?>
就像我说的...一团糟...显然可以进行清洁。除此之外还有清理和重构。我意识到。刚刚上班才决定问一下
你自己做的有多复杂。 :-)
您的数据(在数据库中)以整洁的规范化方式构建。干杯!
现在您必须在 PHP 中以一种漂亮的方式表示它。
我会用一个数组来表示所有内容(除非你有超过一百万个条目,在那种情况下你需要不同的方法)。
我们只需要找到一种方法来记住每个 menu_categories.id 的 menu_types.id。我为此使用了一个简单的数组:$remember_menuID
// assuming you use associative queries
$all = array();
$RS = $db->GetAll("SELECT id, name FROM menu_types;");
foreach ($RS as $one){
$all[$one['id']] = array('menu_type' => $one['name'],
'menu_categories' => array());
}
// fetch all categories
$remember_menuID = array(); // stores the menu_types.id for each menu_categories.id
$RS = $db->GetAll("SELECT id, name, type_id FROM menu_categories;");
foreach ($RS as $one){
$all[$one['type_id']]['menu_categories'][$one["id"]] = array('category_name' => $one['name'],
'menu_items' => array());
$remember_menuID[$one['id']] = $one['type_id'];
}
// and at last the menu_items
$RS = $db->GetAll("SELECT id, name, cat_id, description, price, image FROM menu_items;");
foreach ($RS as $one){
// lookup menu_type belonging to this cat_id
$menu_type_id = $remember_menuID[$one['cat_id']];
$all[$menu_type_id]['menu_categories'][$one["cat_id"]]['menu_items'][] = %one;
}
echo "<pre>";
print_r($all);
echo "<pre>";
未测试。
我觉得这样的 well-formed 问题应该得到更长的答案。
对于这种情况,我强烈建议使用 Doctrine。
然后您可以简单地编写您的 3 个实体,例如:
Type.php
<?php
// src/Type.php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Type
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;
/** @Column(type="string") **/
protected $name;
/** @OneToMany(targetEntity="Category", mappedBy="type") **/
protected $categories;
public function __construct()
{
$this->categories = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function addCategory($category)
{
$category->setType($this);
$this->categories->add($category);
return $this;
}
public function removeCategory($category)
{
$category->setType(null);
$this->categories->remove($category);
return $this;
}
public function getCategories()
{
return $this->categories;
}
}
Category.php
<?php
// src/Category.php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Category
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;
/** @Column(type="string") **/
protected $name;
/**
* @ManyToOne(targetEntity="Type", inversedBy="categories")
* @JoinColumn(name="type_id", referencedColumnName="id")
*/
protected $type;
/** @OneToMany(targetEntity="Item", mappedBy="category") **/
protected $items;
public function __construct()
{
$this->items = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
}
public function addItem($item)
{
$item->setCategory($this);
$this->items->add($item);
return $this;
}
public function removeItem($item)
{
$item->setCategory(null);
$this->items->remove($item);
return $this;
}
public function getItems()
{
return $this->items;
}
}
Item.php
<?php
// src/Item.php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Item
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;
/** @Column(type="string") **/
protected $name;
/**
* @ManyToOne(targetEntity="Category", inversedBy="items")
* @JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getCategory()
{
return $this->category;
}
public function setCategory($category)
{
$this->category = $category;
return $this;
}
}
完成所有这些设置后,Doctrine 将生成您的表格,您可以像这样简单地查询您的信息:
$repo = $entityManager->getRepository("Type");
$kitchen = $repo->findOneBy(array("name" => "Kitchen"));
echo "Fetching 'Kitchen'-Categories...<br/>";
$categories = $kitchen->getCategories();
foreach($categories as $category)
{
$itemsInCategory = $category->getItems();
echo "Category: ".$category->getName().", Items:<br/>";
foreach($itemsInCategory as $item)
{
echo $item->getName()."<br/>";"
}
}
如您所见,此时只需调用 getter 来查询整棵树即可。
这里有两个示例文件向您展示用法:
Creating/Storing 个对象:
<?php
// createTest.php
require_once "bootstrap.php";
// Create 'Bar' Type
$bar = new Type();
$bar->setName("Bar");
$entityManager->persist($bar);
// Create 'Kitchen' Type
$kitchen= new Type();
$kitchen->setName("Kitchen");
$entityManager->persist($kitchen);
// Create 'Salads' Category...
$salads = new Category();
$salads->setName("Salads");
$entityManager->persist($salads);
// ... and add it to the kitchen
$kitchen->addCategory($salads);
// Create Teas and add to Bar
$teas = new Category();
$teas->setName("Teas");
$entityManager->persist($teas);
$bar->addCategory($teas);
// Create Pastries and add to Kitchen
$pastries = new Category();
$pastries->setName("Pastries");
$entityManager->persist($pastries);
$kitchen->addCategory($pastries);
// Add some Items
$caesar = new Item();
$caesar->setName("Caesar Salad");
$entityManager->persist($caesar);
$salads->addItem($caesar);
$entityManager->flush();
查询对象:
<?php
// queryTest.php
require_once "bootstrap.php";
$typeRepo = $entityManager->getRepository("Type");
$types = $typeRepo->findAll();
echo "Found ".count($types)." types:\n";
foreach($types as $type)
{
echo $type->getName()."\n";
foreach($type->getCategories() as $category)
{
echo " - ".$category->getName()."\n";
foreach($category->getItems() as $item)
{
echo " - ".$item->getName()."\n";
}
}
}
输出:
Found 2 types:
Bar
- Teas
Kitchen
- Salads
- Caesar Salad
- Pastries
此时您可以进行各种恶作剧,向您的 类 添加更多 properties/methods 只是声明它们、提供可靠的学说注释和更新数据库的问题。
额外的好处是您数据库独立,该示例使用 sqlite,因为它易于设置,但您也可以使用 mysql 或任何其他 PDO支持的数据库。 Doctrine 还关注 SQL 注入,因为它使用的是准备好的语句。
有关更详细的示例,请查看顶部链接的文档!
首先我会说,是的,我搜索过这个...我正在阅读有关编程的书籍以增加我的知识。目前我还没有找到这个问题的答案。我的应用程序有一个可行的解决方案,但它看起来一团糟。这是 PHP.
情况:我正在创建一个应用程序,其中包含从数据库中的 3 个表中提取的动态菜单(食物):
menu_types:
id name
1 Bar
2 Kitchen
menu_categories:
id name type_id
1 Salads 2
2 Teas 1
3 Pastries 2
menu_items
id name cat_id description price image
1 Caesar 1 'hail Caesar' .00 'image location'
2 Greek 1 'Plato's fav' .00 'image location'
3 Cinnamon Roll 3 'lots-o-sugar' .50 'image location'
还有更多数据,但我想您已经明白了表格中的意思。
我的菜单看起来像这样: (HTML 页) 茶、沙拉和糕点将是单击时仅显示其项目的链接。下面是一个粗略的例子,假设沙拉是当前页面。
**Bar** 'Caesar image', Caesar, hail Caesar, .00
Teas 'Greek image', Greek, Plato's fav, .00
**Kitchen**
Salads
Pastries
目前我将这一切合二为一class。一个对象。我最终构建了三个数组
$this->types = array(
[0] => array(
'id' => 1,
'name' => 'Bar'
),
[1] => array(
'id' => 2,
'name' => 'Kitchen'
)
);
$this->categories = array(
[Bar] => array(
'id' => 2,
'name' => 'Teas',
'type_id' => 1
)
),
[Kitchen] => array(
'id' => 1,
'name' => 'Salads',
'type_id' => 2
),
array(
'id' => 3,
'name' => 'Patries',
'type_id' => 2
)
);
$this->items 有自己的数组,$this->category[id] 是主键。
虽然这一切都变得非常混乱。尝试针对菜单的不同部分遍历这些数组是很糟糕的。我没有包括代码,因为我觉得整个思考过程从根本上是错误的。我不是在找人给我一个完整的代码示例,只是帮助我思考过程。我认为这是编码中最难的部分,思考问题的解决方案。
总而言之,我希望创建一个动态菜单,该菜单既可以根据类别过滤项目,也可以根据类型过滤类别
为了好玩,这是我使用的代码:
menu.php
<?php
class menu{
private $category;
private $size;
private $types;
private $categories;
private $items = array();
public function __construct(){
$this->setTypes();
$this->setCategories();
$this->setItems();
}
private function setTypes(){
$sql = "SELECT * FROM bbc_menu_types";
$this->types = db::rowAsAssocArray($sql);
}
public function getTypes(){
return $this->types;
}
private function setCategories(){
for ($i = 0; $i < count($this->types); $i++){
$typeId = $this->types[$i]['id'];
$sql = "SELECT * FROM bbc_menu_categories WHERE type_id = $typeId";
$this->categories[$this->types[$i]['name']] = db::rowAsAssocArray($sql);
}
}
public function getCategories(){
return $this->categories;
}
public function setItems(){
foreach ($this->categories as $key => $value){
for ($i = 0; $i < count($value); $i++){
$catId = $value[$i]['id'] . '<br />';
settype($catId, 'integer');
$sql = "SELECT * FROM bbc_menu_items WHERE category_id = $catId";
$this->items[$this->categories[$key][$i]['name']] = db::rowAsAssocArray($sql);
}
}
}
public function getItems(){
return $this->items;
}
}
?>
db.pgp(摘录)
public static function rowAsAssocArray($sql){
try{
//do not touch
$data=null;
$stmt = self::$link->prepare($sql);
$stmt->execute();
while ($result = $stmt->fetchAll(PDO::FETCH_ASSOC)){
foreach ($result as $key => $value){
$data[] = $value;
}
}
return $data;
}
catch (PDOException $e){
print $e->getMessage();
}
}
html(专家)
<?php
$i=0;
foreach ($types as $value){
echo "<li><h3>" . $types[$i]['name'] . "</h3></li>";
$i2 = 0;
while ($i2 <count($categories[$types[$i]['name']])){
if ($_GET['cat'] === strtolower($categories[$types[$i]['name']][$i2]['name'])){
echo "<li class='active'><a href='?rt=menu&cat=";
} else {
echo "<li><a href='?rt=menu&cat=";
}
echo strtolower($categories[$types[$i]['name']][$i2]['name']) . "'>" . $categories[$types[$i]['name']][$i2]['name'] . "</a></li>";
$i2++;
}
$i++;
}
?>
</ul>
</nav>
</div><!-- end menu-links -->
</div><!-- end col -->
<div class="col-sm-12 col-md-9">
<div class="menu-links-big">
<?php
$i = 0;
while ($i < count($items[ucfirst($_GET['cat'])])){
?>
<div class="menu-item">
<img src="<?php echo $items[ucfirst($_GET['cat'])][$i]['image']; ?>" alt="" class="img-thumbnail shadow alignleft">
<h3><?php echo $items[ucfirst($_GET['cat'])][$i]['name']; ?></h3>
<p><?php echo $items[ucfirst($_GET['cat'])][$i]['description']; ?></p>
<div class="price"><?php echo '$' . $items[ucfirst($_GET['cat'])][$i]['price']; ?></div>
</div><!-- end item -->
<?php
$i++;
}
?>
就像我说的...一团糟...显然可以进行清洁。除此之外还有清理和重构。我意识到。刚刚上班才决定问一下
你自己做的有多复杂。 :-)
您的数据(在数据库中)以整洁的规范化方式构建。干杯!
现在您必须在 PHP 中以一种漂亮的方式表示它。
我会用一个数组来表示所有内容(除非你有超过一百万个条目,在那种情况下你需要不同的方法)。
我们只需要找到一种方法来记住每个 menu_categories.id 的 menu_types.id。我为此使用了一个简单的数组:$remember_menuID
// assuming you use associative queries
$all = array();
$RS = $db->GetAll("SELECT id, name FROM menu_types;");
foreach ($RS as $one){
$all[$one['id']] = array('menu_type' => $one['name'],
'menu_categories' => array());
}
// fetch all categories
$remember_menuID = array(); // stores the menu_types.id for each menu_categories.id
$RS = $db->GetAll("SELECT id, name, type_id FROM menu_categories;");
foreach ($RS as $one){
$all[$one['type_id']]['menu_categories'][$one["id"]] = array('category_name' => $one['name'],
'menu_items' => array());
$remember_menuID[$one['id']] = $one['type_id'];
}
// and at last the menu_items
$RS = $db->GetAll("SELECT id, name, cat_id, description, price, image FROM menu_items;");
foreach ($RS as $one){
// lookup menu_type belonging to this cat_id
$menu_type_id = $remember_menuID[$one['cat_id']];
$all[$menu_type_id]['menu_categories'][$one["cat_id"]]['menu_items'][] = %one;
}
echo "<pre>";
print_r($all);
echo "<pre>";
未测试。
我觉得这样的 well-formed 问题应该得到更长的答案。
对于这种情况,我强烈建议使用 Doctrine。
然后您可以简单地编写您的 3 个实体,例如:
Type.php
<?php
// src/Type.php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Type
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;
/** @Column(type="string") **/
protected $name;
/** @OneToMany(targetEntity="Category", mappedBy="type") **/
protected $categories;
public function __construct()
{
$this->categories = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function addCategory($category)
{
$category->setType($this);
$this->categories->add($category);
return $this;
}
public function removeCategory($category)
{
$category->setType(null);
$this->categories->remove($category);
return $this;
}
public function getCategories()
{
return $this->categories;
}
}
Category.php
<?php
// src/Category.php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Category
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;
/** @Column(type="string") **/
protected $name;
/**
* @ManyToOne(targetEntity="Type", inversedBy="categories")
* @JoinColumn(name="type_id", referencedColumnName="id")
*/
protected $type;
/** @OneToMany(targetEntity="Item", mappedBy="category") **/
protected $items;
public function __construct()
{
$this->items = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
}
public function addItem($item)
{
$item->setCategory($this);
$this->items->add($item);
return $this;
}
public function removeItem($item)
{
$item->setCategory(null);
$this->items->remove($item);
return $this;
}
public function getItems()
{
return $this->items;
}
}
Item.php
<?php
// src/Item.php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Item
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;
/** @Column(type="string") **/
protected $name;
/**
* @ManyToOne(targetEntity="Category", inversedBy="items")
* @JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getCategory()
{
return $this->category;
}
public function setCategory($category)
{
$this->category = $category;
return $this;
}
}
完成所有这些设置后,Doctrine 将生成您的表格,您可以像这样简单地查询您的信息:
$repo = $entityManager->getRepository("Type");
$kitchen = $repo->findOneBy(array("name" => "Kitchen"));
echo "Fetching 'Kitchen'-Categories...<br/>";
$categories = $kitchen->getCategories();
foreach($categories as $category)
{
$itemsInCategory = $category->getItems();
echo "Category: ".$category->getName().", Items:<br/>";
foreach($itemsInCategory as $item)
{
echo $item->getName()."<br/>";"
}
}
如您所见,此时只需调用 getter 来查询整棵树即可。
这里有两个示例文件向您展示用法:
Creating/Storing 个对象:
<?php
// createTest.php
require_once "bootstrap.php";
// Create 'Bar' Type
$bar = new Type();
$bar->setName("Bar");
$entityManager->persist($bar);
// Create 'Kitchen' Type
$kitchen= new Type();
$kitchen->setName("Kitchen");
$entityManager->persist($kitchen);
// Create 'Salads' Category...
$salads = new Category();
$salads->setName("Salads");
$entityManager->persist($salads);
// ... and add it to the kitchen
$kitchen->addCategory($salads);
// Create Teas and add to Bar
$teas = new Category();
$teas->setName("Teas");
$entityManager->persist($teas);
$bar->addCategory($teas);
// Create Pastries and add to Kitchen
$pastries = new Category();
$pastries->setName("Pastries");
$entityManager->persist($pastries);
$kitchen->addCategory($pastries);
// Add some Items
$caesar = new Item();
$caesar->setName("Caesar Salad");
$entityManager->persist($caesar);
$salads->addItem($caesar);
$entityManager->flush();
查询对象:
<?php
// queryTest.php
require_once "bootstrap.php";
$typeRepo = $entityManager->getRepository("Type");
$types = $typeRepo->findAll();
echo "Found ".count($types)." types:\n";
foreach($types as $type)
{
echo $type->getName()."\n";
foreach($type->getCategories() as $category)
{
echo " - ".$category->getName()."\n";
foreach($category->getItems() as $item)
{
echo " - ".$item->getName()."\n";
}
}
}
输出:
Found 2 types:
Bar
- Teas
Kitchen
- Salads
- Caesar Salad
- Pastries
此时您可以进行各种恶作剧,向您的 类 添加更多 properties/methods 只是声明它们、提供可靠的学说注释和更新数据库的问题。
额外的好处是您数据库独立,该示例使用 sqlite,因为它易于设置,但您也可以使用 mysql 或任何其他 PDO支持的数据库。 Doctrine 还关注 SQL 注入,因为它使用的是准备好的语句。
有关更详细的示例,请查看顶部链接的文档!