From 708f73ccc91d8b83970a7aa4d0e07e39a5f1a892 Mon Sep 17 00:00:00 2001 From: Andrew Nacin Date: Sun, 29 Jun 2014 21:26:17 +0000 Subject: [PATCH] =?UTF-8?q?Add=20index=20key=20support=20for=20wp=5Flist?= =?UTF-8?q?=5Fpluck(),=20=C3=A0=20la=20array=5Fcolumn().?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- wp-includes/functions.php | 44 ++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/wp-includes/functions.php b/wp-includes/functions.php index 94d6de3eb5..bee66303df 100644 --- a/wp-includes/functions.php +++ b/wp-includes/functions.php @@ -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 ) { - foreach ( $list as $key => $value ) { - if ( is_object( $value ) ) - $list[ $key ] = $value->$field; - else - $list[ $key ] = $value[ $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 ) ) { + $list[ $key ] = $value->$field; + } else { + $list[ $key ] = $value[ $field ]; + } + } + return $list; } - 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; } /**