WP_List_Util::pluck( int|string $field, int|string $index_key = null )
Plucks a certain field out of each element in the input array.
Description
This has the same functionality and prototype of array_column() (PHP 5.5) but also supports objects.
Parameters
- $field
-
(Required) Field to fetch from the object or array.
- $index_key
-
(Optional) Field from the element to use as keys for the new array.<br>
Default value: 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.
Source
File: wp-includes/class-wp-list-util.php
public function pluck( $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 ( $this->output as $key => $value ) {
if ( is_object( $value ) ) {
$this->output[ $key ] = $value->$field;
} else {
$this->output[ $key ] = $value[ $field ];
}
}
return $this->output;
}
/*
* 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 ( $this->output 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 ];
}
}
}
$this->output = $newlist;
return $this->output;
}
Changelog
Version | Description |
---|---|
4.7.0 | Introduced. |