goranseric
6/9/2017 - 7:09 PM

For WordPress, a method to re-index a multi-dimensional array by the (unique) value of a given array key

For WordPress, a method to re-index a multi-dimensional array by the (unique) value of a given array key

<?php

/**
 * Plucks a value from an array and re-indexes the array
 * with the value of that key as the key of that item in the array.
 *
 * WARNING: the value of the key you choose MUST be unique.
 *
 * @param array $array The array to process.
 * @param string $key The key to pluck the value from.
 * @return array The modified array.
 */
public static function reindex_by_array_key( array $array, string $key ) {
  return array_column( $array, null, $key );
}

Okay, so, let's say you have some data like this:

$things = [
  0 => [ 'id' => 123, 'title' => '123 Title', 'content' => '123 Content' ],
  1 => [ 'id' => 456, 'title' => '456 Title', 'content' => '456 Content' ],
  2 => [ 'id' => 789, 'title' => '789 Title', 'content' => '789 Content' ],
];

Those numerical indexes aren't very useful. If id is a unique key, it would be much more useful if it were indexed with the id value as the array key.

So you just do:

$things = self::reindex_by_array_key( $things, 'id' );

And now you have:

$things = [
  123 => [ 'id' => 123, 'title' => '123 Title', 'content' => '123 Content' ],
  456 => [ 'id' => 456, 'title' => '456 Title', 'content' => '456 Content' ],
  789 => [ 'id' => 789, 'title' => '789 Title', 'content' => '789 Content' ],
];

And now you can do isset( $things[$id_to_test] ) ) to see if an item with a given id exists in the array.

Note

This code was written for PHP 7.0+.

I was using wp_list_pluck() until Lionel told me about array_column().

What other handy helpers do you use?