Skip to content

Instantly share code, notes, and snippets.

@markjaquith

markjaquith/readme.md

Last active Jun 11, 2017
Embed
What would you like to do?
For WordPress, a method to re-index a multi-dimensional array by the (unique) value of a given array 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?

<?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 );
}
@markjaquith

This comment has been minimized.

Copy link
Owner Author

@markjaquith markjaquith commented Jun 11, 2017

Lionel found a way to do this with a PHP core function! It's PHP 5.5+ and I somehow haven't heard of it until now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.