如何在 PHP 中创建对象列表或数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/963282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:30:02  来源:igfitidea点击:

How do I create a list or an array of objects in PHP?

php

提问by OneSmartGuy

I'm a .net programmer vb & c#, but I can't seem to figure out how to get my objects into a list or array in PHP.

我是 .net 程序员 vb & c#,但我似乎无法弄清楚如何将我的对象放入 PHP 中的列表或数组中。

var mylist = new List<myobject>();

mylist.add(myobject1);
mylist.add(myobject2);

What I have tried.
Products being a property for a collection of orderitems:

我尝试过的。
产品是以下集合的属性orderitems

$this->Products = getOrderItems();

public function getOrderItems()
{
    $items = array();
    $count = 0;

      // connect to db, query.....

    while($row = mysql_fetch_array($result, MYSQL_BOTH)){
        $count++;
        $items[$count] = ($row);
    }
    echo 'Count of Order Items...' . $count;

    return $items;
}

Am I even close?

我什至接近吗?

回答by moo

$items = array();

while($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    $items[] = $row;
}
echo 'Count of Order Items...', count($items);

回答by stefs

  • $this->Products = getOrderItems();is legal in PHP, but it refers to the (global) function getOrderItems()instead of the class method. class methods and variables always have to be prefixed with $this->(or self::, if they're static vars) when called from inside the class.
    in your sample-code, you have that wrong. getOrderItems is defined as class method, but your call is not $this->-scoped, thus php assumes a function. it should throw an function not found-error.

  • the []notation adds an element to the end of an array.

  • the index of the first element in your sample code is 1 (isn't that the standard case for VB?). php normally starts at 0 - though it's possible (because php-arrays are not real arrays) to start at arbitrary indices i'd recommend to stick with zero.

  • mysql_fetch_arrayis an ancientway of working with mysql. nowadays you're better of with mysqli or (even better) PDO.

  • (...) a list or array in php.

    lists, arrays, stacks, whatever: in php everthing is an ordered map (misleadingly called array):

    PHP: Arrays: An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

  • $this->Products = getOrderItems();在 PHP 中是合法的,但它指的是(全局)函数getOrderItems()而不是类方法。从类内部调用时,类方法和变量总是必须以$this->(或self::,如果它们是静态变量)为前缀。
    在您的示例代码中,您错了。getOrderItems 被定义为类方法,但您的调用不是$this->范围的,因此 php 假定一个函数。它应该抛出一个function not found错误。

  • []表示法将一个元素添加到数组的末尾。

  • 示例代码中第一个元素的索引是 1(这不是 VB 的标准情况吗?)。php 通常从 0 开始 - 尽管有可能(因为 php 数组不是真正的数组)从任意索引开始,我建议坚持使用零。

  • mysql_fetch_array是一种使用 mysql的古老方式。现在你更喜欢使用 mysqli 或(甚至更好)PDO。

  • (...) php 中的列表或数组。

    列表、数组、堆栈等等:在 php 中,一切都是有序映射(误导性地称为数组):

    PHP: Arrays: PHP 中的数组实际上是一个有序映射。映射是一种将值与键相关联的类型。此类型针对多种不同用途进行了优化;它可以被视为数组、列表(向量)、哈希表(映射的实现)、字典、集合、堆栈、队列等等。由于数组值可以是其他数组,树和多维数组也是可能的。

update:

更新:

sorry, i haven't got enough time right now to explain the finer nuances of pdo/mysqliover mysql.

抱歉,我现在没有足够的时间来解释pdo/ mysqlimysql 之间的细微差别。

so here are just the basics:

所以这里只是基础知识:

  • oop:pdo and mysqli are object oriented (tough mysqli got functional aliases)

  • prep statements:most important: pdo/mysqli got prepared statements. that means, you first prepare the query with placeholders once, then fill in the values later (without the need to prepare the query a second time). this approach has 3 obvious advantages:

    • performance:it's faster, because the database only has to analyze, compile and optimize the query once (at least with complex queries)

    • security:no need for quoted strings (happens automatically!), making sql-injection attacks harder

    • maintainability:the logic and data part of the query are separated, thus easier to read and you don't have to do a lot of string concenation

  • driver driven:pdo is not database specific. there are several supported db-systems, making it easier to port your code to other db-backends (but it's not an db-abstraction layer like ODBC, so the SQL still has to be compatible)and increasing reusability

  • oop:pdo 和 mysqli 是面向对象的(艰难的 mysqli 有功能别名)

  • 准备语句:最重要的是:pdo/mysqli 得到了准备好的语句。这意味着,您首先使用占位符准备一次查询,然后稍后填写值(无需再次准备查询)。这种方法有 3 个明显的优点:

    • 性能:更快,因为数据库只需要分析、编译和优化一次查询(至少对于复杂的查询)

    • 安全性:不需要带引号的字符串(自动发生!),使 sql 注入攻击更加困难

    • 可维护性:查询的逻辑部分和数据部分是分离的,因此更易于阅读,您不必进行大量的字符串合并

  • 驱动程序驱动:pdo 不是特定于数据库的。有几个受支持的数据库系统,可以更轻松地将代码移植到其他数据库后端(但它不是像 ODBC 那样的数据库抽象层,因此 SQL 仍然必须兼容)并提高可重用性

of course, there's a lot more to it

当然,还有很多

回答by John Fiala

What orlandu63 posted is correct - using $items[] = $rowmeans that $row is appended numerically as the next element of $items.

orlandu63 发布的内容是正确的 - 使用$items[] = $row意味着 $row 以数字方式附加为 $items 的下一个元素。

Another option is that if there's an id field in $row, you can do $items[$row->id] = $row;, which has the advantage of indexing your array and making it easier to find a given item.

另一种选择是,如果 $row 中有一个 id 字段,您可以执行$items[$row->id] = $row;,这具有索引数组并更容易找到给定项目的优点。

I really suggest reading through http://www.php.net/manual/en/language.types.array.php, which will explain to you some of the cool things PHP allows with arrays.

我真的建议通读http://www.php.net/manual/en/language.types.array.php,它会向您解释 PHP 允许使用数组的一些很酷的东西。