1

For example an array that has all the months, inside each month are all the users registered that month, and details on every user. I could solve it by simply searching for all users registered this year, then put the results through a loop that builds the array I want by detecting when there is a change in the 6th and 7th characters of the "date" field (example: 2016-04-05), but I am wondering if there is a more "official" way.

2
  • Why do you need to detect changes to the month in user registration dates? Registration dates don't change...
    – bosco
    May 4, 2016 at 19:33
  • @bosco I meant change between different users. When the current user's month is different than the previous one the code would start assigning the users to a new field of the array.
    – Nadroev
    May 4, 2016 at 19:41

1 Answer 1

2

The direct answer to the question "Is there a way to get 3+ dimensional array from a single MySql command" would be yes, sort of - WordPress routinely stores and retrieves multidimensional data from MySQL rows by serialize()ing and unserialize()ing structured data to/from a string format, so it's certainly possible using WordPress's database interaction mechanisms. The Metadata API automatically handles this process when you pass it structured data, for example.

However, your question is rather something more along the lines of "How can I restructure database results into a custom format?"

The most "WordPress-y" way would be as you describe - use a WP_User_Query to query for users then re-arrange the results into your desired structure.

It may be possible to create a custom SQL query that formats the results as you desire but it seems counter-intuitive - relational databases are designed with a large emphasis on 2-dimensional data. Inquire over at Stack Overflow if you'd be interested in such a query. You can execute custom queries in WordPress using the parse_query() method of WP_Query.

To acquire a structure of users who registered within a certain year grouped by month of registration, I would do the following:

function wpse225632_get_users_by_reg_month( $year = null ) {
  $args = array();

  if( isset( $year ) )
    $args[ 'date_query' ] = array( 'year' => $year );

  $users          = get_users( $args );
  $users_by_month = array();

  foreach( $users as $user ) {
    $reg_month = mysql2date( 'm', $user->user_registered );

    if( ! isset( $users_by_month[ $reg_month ] ) )
      $users_by_month[ $reg_month ] = array();

    $users_by_month[ $reg_month ][] = $user;
  }

  return $users_by_month;
}

If you'll be running this query frequently, you may wish to cache the resulting array using the Transients API, then invalidate the cache and delete the transient whenever a new user is registered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.