Created
February 13, 2021 15:05
-
-
Save mircobabini/ca320e151b2efbcca940875c0052ff69 to your computer and use it in GitHub Desktop.
This file contains 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 | |
/** | |
* Pluck a certain field out of each object in a list. | |
* | |
* This has the same functionality and prototype of | |
* array_column() (PHP 5.5) but also supports objects. | |
* | |
* @param array $list List of objects or arrays | |
* @param int|string $field Field from the object to place instead of the entire object | |
* @param int|string $index_key Optional. Field from the object to use as keys for the new array. | |
* Default null. | |
* @return array Array of found values. If `$index_key` is set, an array of found values with keys | |
* corresponding to `$index_key`. If `$index_key` is null, array keys from the original | |
* `$list` will be preserved in the results. | |
*/ | |
function wp_list_pluck( $oldlist, $field, $index_key = null ) { | |
$newlist = array(); | |
if ( ! $index_key ) { | |
/* | |
* This is simple. Could at some point wrap array_column() | |
* if we knew we had an array of arrays. | |
*/ | |
foreach ( $oldlist as $key => $value ) { | |
if ( is_object( $value ) ) { | |
$newlist[ $key ] = $value->$field; | |
} else { | |
$newlist[ $key ] = $value[ $field ]; | |
} | |
} | |
return $newlist; | |
} | |
/* | |
* When index_key is not set for a particular item, push the value | |
* to the end of the stack. This is how array_column() behaves. | |
*/ | |
foreach ( $oldlist as $value ) { | |
if ( is_object( $value ) ) { | |
if ( isset( $value->$index_key ) ) { | |
$newlist[ $value->$index_key ] = $value->$field; | |
} else { | |
$newlist[] = $value->$field; | |
} | |
} else { | |
if ( isset( $value[ $index_key ] ) ) { | |
$newlist[ $value[ $index_key ] ] = $value[ $field ]; | |
} else { | |
$newlist[] = $value[ $field ]; | |
} | |
} | |
} | |
return $newlist; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment