Add index key support for wp_list_pluck(), à la array_column().

props trepmal.
fixes #28666.


git-svn-id: https://develop.svn.wordpress.org/trunk@28900 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Andrew Nacin
2014-06-29 21:25:21 +00:00
parent 1388b15b67
commit 02094174f9
2 changed files with 84 additions and 10 deletions
+37 -7
View File
@@ -2882,21 +2882,51 @@ function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
/**
* 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.
*
* @since 3.1.0
*
* @param array $list A list of objects or arrays
* @param int|string $field A field from the object to place instead of the entire object
* @param int|string $index_key A field from the object to use as keys for the new array
* @return array
*/
function wp_list_pluck( $list, $field ) {
foreach ( $list as $key => $value ) {
if ( is_object( $value ) )
$list[ $key ] = $value->$field;
else
$list[ $key ] = $value[ $field ];
function wp_list_pluck( $list, $field, $index_key = null ) {
if ( ! $index_key ) {
// This is simple. Could at some point wrap array_column()
// if we knew we had an array of arrays.
foreach ( $list as $key => $value ) {
if ( is_object( $value ) ) {
$list[ $key ] = $value->$field;
} else {
$list[ $key ] = $value[ $field ];
}
}
return $list;
}
return $list;
// 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.
$newlist = array();
foreach ( $list 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;
}
/**