【问题标题】:PHP Array of Objects; Get object where $object->id == 2PHP 对象数组;获取 $object->id == 2 的对象
【发布时间】:2018-05-27 14:33:56
【问题描述】:

我有班级“list_member”:

class list_member
{
  public $id;
  public $email;
  public $lastchange;
  public $active;
  public $hash;
  public $list_id;

  function __construct($id,$email,$lastchange,$active,$hash,$list_id)
  {
    $this->id = $id;
    $this->email = $email;
    $this->lastchange = $lastchange;
    $this->active = $active;
    $this->hash = $hash;
    $this->list_id = $list_id;
  }
}

我有一个 list_members 数组。现在我想获得具有唯一 id ($this->id) 的成员,例如42.

如果不遍历整个数组并检查每个条目,这怎么可能?

【问题讨论】:

标签: php arrays object


【解决方案1】:

在不进行数组查找的情况下按类成员进行搜索的一种选择是使用哈希表对查找属性进行索引。这会将负担从您的处理器转移到您的内存中。

您可以通过包含id 的静态映射并提供查找方法来修改您的原始类。由于id 在这种情况下是唯一的,因此我演示了一个验证检查,如果您尝试实例化具有相同值的两个成员,该验证检查将通过引发异常来停止执行。

class list_member
{
  public $id;
  public $email;
  private static $ids = array();

  function __construct($id,$email)
  {
    $this->id = $id;
    $this->email = $email;

    if ( array_key_exists( $id, self::$ids ) ) {
        throw new Exception('Item with id ' . $id . ' already exists.');
    }
    self::$ids[$id] = &$this;
  }

  public static function lookup_by_id($id) {
    return self::$ids[$id];
  }
}


new list_member(5, 'username1@email.com');
new list_member(15, 'username2@email.com');
new list_member(42, 'username3@email.com');
new list_member(45, 'username4@email.com');

$member = list_member::lookup_by_id(45);
echo $member->email; // username4@email.com

【讨论】:

  • 谢谢。当我创建数组时,我只是做$members_list[$id] = new list_member(***);
  • 所有数据都存储在 SQL 数据库中,所以我不必担心 Id。
  • @HannesKeks 您是否使用 PDO 从数据库中检索结果集?它们是填充类对象的替代方法。例如$pdo->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_GROUP, list_member::class) 将生成由查询的第一列索引的 list_member 对象数组。这样你也不需要遍历数据库结果来构建你的对象。
猜你喜欢
  • 1970-01-01
  • 2020-08-07
  • 2019-06-05
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多