Ottieni un elenco di tutti gli utenti e in un array


17

Mi chiedevo come ottenere tutti gli utenti e mettere tutti i loro UID in un array? Ho visto domande simili, ma nessuna risponde davvero alla mia domanda.

Risposte:


18

In Drupal 7 puoi recuperare tutti gli utenti usando entity_load come segue,

$users = entity_load('user');

e array_keys ($ users) ti darà l'array di uid


9

Puoi ottenere il risultato in Drupal 8:

$query = \Drupal::entityQuery('user');

$uids = $query->execute();

1

Sto solo condividendo uno snippet che ho creato di recente per ottenere HTML e EMAIL di tutti gli utenti esistenti nel database.

Funziona bene con oltre 2000 utenti. Successivamente suggerisco di implementare il batch o una query di database diretta alternativa.

Questo si basa sul caricamento di Drupal da parte di ciascun utente.

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'user');
$html = '<table>';
$result = $query->execute();

$uids = array_keys($result['user']);

// THIS IS YOUR ARRAY OF UIDS.
$users = user_load_multiple($uids);

// EXTRA CODE.
foreach($users as $user){
  $mail = $user->mail;
  $name = $user->name;
  $html .= '<tr><td>'.$mail.'</td>'.'<td>'.$name.'</td></tr>';
}
$html .= '</table'>;

Restituirà una semplice tabella html che puoi copiare facilmente in eccelle ecc.

Per ottenerli in un array è sufficiente utilizzare la variabile indicata nel codice per UIDS.


0

Per rispondere ad alcuni dei commenti: se stai lavorando con un gran numero di utenti non sarai in grado di caricare tutti gli utenti in un array senza timeout, quindi probabilmente dovrai elaborarli in batch ...

Ecco come (sì è:

 function _set_batch_revench_agains_users(){
  $batch = [
    'operations' => [
      ['_revench_against_users_batch_process']
    ],
    'finished' => '_revench_against_users_batch_finished',
    'title' => t('Punishing users for ungratefulness and general insolence.'),
    'init_message' => t('Batch is starting, he he he...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Batch has encountered an error, nooooo!'),
    'file' => drupal_get_path('module', 'revench_agains_users') . '/user_agains_users.module'
  ];
  batch_set($batch);
  batch_process('admin');
}

/**
 * Batch 'Processing' callback
 */

function _revench_against_users_batch_process(&$context){
 //all this $context stuff is mandatory, it is a bit heavy, but the batchAPI need it to keep track of progresses
  if (!isset($context['sandbox']['current'])) {
    $context['sandbox']['count'] = 0;
    $context['sandbox']['current'] = 0;
  }

  //don't use entity field query for such simple use cases as gettings all ids (much better performances, less code to write...)
  $query =  db_select('users', 'u');
  $query->addField('u', 'uid');
  $query->condition('u.uid', $context['sandbox']['current'], '>');
  $query->orderBy('u.uid');
  // Get the total amount of items to process.
  if (!isset($context['sandbox']['total'])) {
    $context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();

    // If there are no users to "update", stop immediately.
    if (!$context['sandbox']['total']) {
      $context['finished'] = 1;
      return;
    }
  }

  $query->range(0, 25);
  $uids = $query->execute()->fetchCol();
  //finaly ! here is your user array, limited to a manageable chunk of 25 users
  $users_array = user_load_multiple($uids);
  //send it to some function to "process"...
  _burn_users_burnburnburn($users_array); // I won't reveal the content of this function for legal reasons
  //more mandatory context stuff
  $context['sandbox']['count'] += count($uids);
  $context['sandbox']['current'] = max($uids);
  $context['message'] = t('burned @uid ... feels better ...', array('@uid' => end($uids)));

  if ($context['sandbox']['count'] != $context['sandbox']['total']) {
    $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
  }

}

/**
 * Batch 'finished' callback
 */
function _revench_against_users_batch_finished($success, $results, $operations) {
  if ($success) {
    // Here we do something meaningful with the results.
    $message = t('@count users successfully burned:', array('@count' => count($results)));

    drupal_set_message($message);
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments some users might have escaped !', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
    drupal_set_message($message, 'error');
  }
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.