Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Last active September 20, 2017 23:19
Show Gist options
  • Save wpscholar/8939717 to your computer and use it in GitHub Desktop.
Save wpscholar/8939717 to your computer and use it in GitHub Desktop.
Index a collection of arrays/objects by a specific key/property.
<?php
/**
* Index a collection of arrays/objects by a specific key/property.
*
* @param string $index
* @param array $data
* @return array
*/
function index_by( $index, array $data ) {
$indexed_data = array();
foreach( $data as $item ) {
if( is_array( $item ) && array_key_exists( $index, $item ) ) {
$indexed_data[$item[$index]] = $item;
} else if( is_object( $item ) && property_exists( $item, $index ) ) {
$indexed_data[$item->$index] = $item;
}
}
return $indexed_data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment