wp_list_pluck

Pluck a certain field out of each object in a list.

Description

(array) wp_list_pluck( (array) $list, (int|string) $field, (null) $index_key = null ); 

This has the same functionality and prototype of array_column() (PHP 5.5) but also supports objects.

Returns (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.

Parameters (3)

0. $list (array)
List of objects or arrays
1. $field (int|string)
Field from the object to place instead of the entire object
2. $index_key — Optional. (null) => null
Field from the object to use as keys for the new array. Default null.

Usage

  1. if ( !function_exists( 'wp_list_pluck' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4. // List of objects or arrays 
  5. $list = array(); 
  6.  
  7. // Field from the object to place instead of the entire object 
  8. $field = null; 
  9.  
  10. // Optional. Field from the object to use as keys for the new array. 
  11. // Default null. 
  12. $index_key = null; 
  13.  
  14. // NOTICE! Understand what this does before running. 
  15. $result = wp_list_pluck($list, $field, $index_key); 
  16.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/functions.php  
  1. function wp_list_pluck( $list, $field, $index_key = null ) { 
  2. if ( ! $index_key ) { 
  3. /** 
  4. * This is simple. Could at some point wrap array_column() 
  5. * if we knew we had an array of arrays. 
  6. */ 
  7. foreach ( $list as $key => $value ) { 
  8. if ( is_object( $value ) ) { 
  9. $list[ $key ] = $value->$field; 
  10. } else { 
  11. $list[ $key ] = $value[ $field ]; 
  12. return $list; 
  13.  
  14. /** 
  15. * When index_key is not set for a particular item, push the value 
  16. * to the end of the stack. This is how array_column() behaves. 
  17. */ 
  18. $newlist = array(); 
  19. foreach ( $list as $value ) { 
  20. if ( is_object( $value ) ) { 
  21. if ( isset( $value->$index_key ) ) { 
  22. $newlist[ $value->$index_key ] = $value->$field; 
  23. } else { 
  24. $newlist[] = $value->$field; 
  25. } else { 
  26. if ( isset( $value[ $index_key ] ) ) { 
  27. $newlist[ $value[ $index_key ] ] = $value[ $field ]; 
  28. } else { 
  29. $newlist[] = $value[ $field ]; 
  30.  
  31. return $newlist;