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:
parent
5f08eed052
commit
708f73ccc9
|
@ -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 ) {
|
||||
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 ) )
|
||||
if ( is_object( $value ) ) {
|
||||
$list[ $key ] = $value->$field;
|
||||
else
|
||||
} else {
|
||||
$list[ $key ] = $value[ $field ];
|
||||
}
|
||||
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
Loading…
Reference in New Issue