jimboobrien
9/20/2017 - 11:19 PM

Index a collection of arrays/objects by a specific key/property.

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;
}