wc_list_pluck()
Based on wp_list_pluck, this calls a method instead of returning a property.
No Hooks.
Returns
Array. Array of values.
Usage
wc_list_pluck( $list, $callback_or_field, $index_key );
- $list(array) (required)
- List of objects or arrays.
- $callback_or_field(int|string) (required)
- Callback method from the object to place instead of the entire object.
- $index_key(int|string)
- Field from the object to use as keys for the new array.
Default: null
Changelog
| Since 3.0.0 | Introduced. |
wc_list_pluck() wc list pluck code WC 10.3.6
function wc_list_pluck( $list, $callback_or_field, $index_key = null ) {
// Use wp_list_pluck if this isn't a callback.
$first_el = current( $list );
if ( ! is_object( $first_el ) || ! is_callable( array( $first_el, $callback_or_field ) ) ) {
return wp_list_pluck( $list, $callback_or_field, $index_key );
}
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 ) {
$list[ $key ] = $value->{$callback_or_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 ) {
// Get index. @since 3.2.0 this supports a callback.
if ( is_callable( array( $value, $index_key ) ) ) {
$newlist[ $value->{$index_key}() ] = $value->{$callback_or_field}();
} elseif ( isset( $value->$index_key ) ) {
$newlist[ $value->$index_key ] = $value->{$callback_or_field}();
} else {
$newlist[] = $value->{$callback_or_field}();
}
}
return $newlist;
}