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

props trepmal.
fixes #28666.

Built from https://develop.svn.wordpress.org/trunk@28900


git-svn-id: http://core.svn.wordpress.org/trunk@28699 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Andrew Nacin 2014-06-29 21:26:17 +00:00
parent 5f08eed052
commit 708f73ccc9

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