You are here

public function StatementWrapper::fetchAllAssoc in Drupal 9

Returns the result set as an associative array keyed by the given field.

If the given key appears multiple times, later records will overwrite earlier ones.

Parameters

$key: The name of the field on which to index the array.

$fetch: The fetchmode to use. If set to PDO::FETCH_ASSOC, PDO::FETCH_NUM, or PDO::FETCH_BOTH the returned value with be an array of arrays. For any other value it will be an array of objects. By default, the fetch mode set for the query will be used.

Return value

An associative array, or an empty array if there is no result set.

Overrides StatementInterface::fetchAllAssoc

File

core/lib/Drupal/Core/Database/StatementWrapper.php, line 172

Class

StatementWrapper
Implementation of StatementInterface encapsulating PDOStatement.

Namespace

Drupal\Core\Database

Code

public function fetchAllAssoc($key, $fetch = NULL) {
  $return = [];
  if (isset($fetch)) {
    if (is_string($fetch)) {
      $this
        ->setFetchMode(\PDO::FETCH_CLASS, $fetch);
    }
    else {
      $this
        ->setFetchMode($fetch);
    }
  }
  foreach ($this as $record) {
    $record_key = is_object($record) ? $record->{$key} : $record[$key];
    $return[$record_key] = $record;
  }
  return $return;
}