Make WordPress Core


Ignore:
Timestamp:
06/29/2014 09:25:21 PM (10 years ago)
Author:
nacin
Message:

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

props trepmal.
fixes #28666.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/functions.php

    r28894 r28900  
    28832883 * Pluck a certain field out of each object in a list.
    28842884 *
     2885 * This has the same functionality and prototype of
     2886 * array_column() (PHP 5.5) but also supports objects.
     2887 *
    28852888 * @since 3.1.0
    28862889 *
    28872890 * @param array $list A list of objects or arrays
    28882891 * @param int|string $field A field from the object to place instead of the entire object
     2892 * @param int|string $index_key A field from the object to use as keys for the new array
    28892893 * @return array
    28902894 */
    2891 function wp_list_pluck( $list, $field ) {
    2892     foreach ( $list as $key => $value ) {
    2893         if ( is_object( $value ) )
    2894             $list[ $key ] = $value->$field;
    2895         else
    2896             $list[ $key ] = $value[ $field ];
    2897     }
    2898 
    2899     return $list;
     2895function wp_list_pluck( $list, $field, $index_key = null ) {
     2896    if ( ! $index_key ) {
     2897        // This is simple. Could at some point wrap array_column()
     2898        // if we knew we had an array of arrays.
     2899        foreach ( $list as $key => $value ) {
     2900            if ( is_object( $value ) ) {
     2901                $list[ $key ] = $value->$field;
     2902            } else {
     2903                $list[ $key ] = $value[ $field ];
     2904            }
     2905        }
     2906        return $list;
     2907    }
     2908
     2909    // When index_key is not set for a particular item,
     2910    // push the value to the end of the stack.
     2911    // This is how array_column() behaves.
     2912    $newlist = array();
     2913    foreach ( $list as $value ) {
     2914        if ( is_object( $value ) ) {
     2915            if ( isset( $value->$index_key ) ) {
     2916                $newlist[ $value->$index_key ] = $value->$field;
     2917            } else {
     2918                $newlist[] = $value->$field;
     2919            }
     2920        } else {
     2921            if ( isset( $value[ $index_key ] ) ) {
     2922                $newlist[ $value[ $index_key ] ] = $value[ $field ];
     2923            } else {
     2924                $newlist[] = $value[ $field ];
     2925            }
     2926        }
     2927    }
     2928
     2929    return $newlist;
    29002930}
    29012931
Note: See TracChangeset for help on using the changeset viewer.