-
-
Save jimboobrien/5d7e2af796d93c6d958cc186a8ffddc0 to your computer and use it in GitHub Desktop.
Index a collection of arrays/objects by a specific key/property.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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