Make WordPress Core

Opened 10 years ago

Closed 10 years ago

#28666 closed enhancement (fixed)

Index key support for wp_list_pluck(), à la array_column()

Reported by: trepmal's profile trepmal Owned by:
Milestone: 4.0 Priority: normal
Severity: normal Version:
Component: General Keywords:
Focuses: Cc:

Description

PHP 5.5's array_column() has a neat third argument for specifying a field to use as the key for the new array. Patch adds a third optional argument to wp_list_pluck() that mimics that behavior.

Current functionality is this:

wp_list_pluck( get_posts( ), 'post_title' );

which returns an array like

Array
(
    [0] => Hello World!
    [1] => Markup: HTML Tags and Formatting
    [2] => Markup: Image Alignment
    [3] => Markup: Text Alignment
    [4] => Markup: Title With Special Characters ~`!@#$%^&*()-_=+{}[]/;:'"?,.>
)

With the patch, you could specify a field to use as the new keys, so

wp_list_pluck( get_posts( ), 'post_title', 'ID' );

would return

Array
(
    [1699] => Hello World!
    [1178] => Markup: HTML Tags and Formatting
    [1177] => Markup: Image Alignment
    [1176] => Markup: Text Alignment
    [1174] => Markup: Title With Special Characters ~`!@#$%^&*()-_=+{}[]/;:'"?,.>
)

Attachments (2)

28666.diff (1.2 KB) - added by trepmal 10 years ago.
28666.2.diff (4.3 KB) - added by trepmal 10 years ago.

Download all attachments as: .zip

Change History (8)

@trepmal
10 years ago

#1 @DrewAPicture
10 years ago

  • Keywords needs-patch added

Neat-o. +1 for this.

#2 @DrewAPicture
10 years ago

  • Keywords has-patch added; needs-patch removed

derp. See 28666.diff.

#3 @nacin
10 years ago

  • Keywords needs-patch added; has-patch removed
  • Milestone changed from Awaiting Review to 4.0

To optimize the speed of this as much as possible, can we put the if conditional outside of two different foreach loops? We should also reduce the is_object() calls to once per foreach iteration.

We should include in the description for this function that this is an implementation of array_column() that also works with objects.

I wish it only supported all objects or all arrays. As written, it does an is_object() each time. If we somehow knew it was an array of arrays, we could just have this wrap array_column() and get the performance benefits of C.

This ticket was mentioned in IRC in #wordpress-dev by nacin. View the logs.


10 years ago

@trepmal
10 years ago

#5 @trepmal
10 years ago

updated patch with tests!

#6 @SergeyBiryukov
10 years ago

  • Keywords needs-patch removed
  • Resolution set to fixed
  • Status changed from new to closed

Fixed in [28900].

Note: See TracTickets for help on using tickets.