Pluck Fields Out Of an Object or Array

Some days ago I was working on a project and I needed to get out of an object some data, but not all of them. Specifically, I had many terms, and I needed to get only the key name from that object.

What I would have done, is looping though all the items and build an array from that with their names. But I learned about a better way!

Meet wp_list_pluck

wp_list_pluck is a default WordPress function that plucks a certain field out of an object or an array. It’s very easy to use, look at this example:


$foods = array(
array(
'id' => 4,
'name' => 'Banana',
'color' => 'Yellow',
),
array(
'id' => '5',
'name' => 'Apple',
'color' => 'Red',
),
array(
'id' => 2,
'name' => 'Lettuce',
'color' => 'Green',
),
array(
'id' => '7',
'name' => 'Apple',
'color' => 'Red',
),
);
$foods = wp_list_pluck( $foods, 'name' );

view raw

index.php

hosted with ❤ by GitHub

If you check what $foods contains now you will get this:

array(
    'Banana',
    'Apple',
    'Lettuce',
    'Apple'
);

What happened here is that the function extracted all the names from the multi-dimensional array and created a new array with only those names.

The same could be done with objects.

You also need to know that wp_list_pluck supports a third parameter. You can specify another key from the original array that will be used as key for the values in the new array. Looking at the example above, if I use $foods = wp_list_pluck( $foods, 'name', 'id' ); I’d get this array as result:

array(
    4 => 'Banana',
    5 => 'Apple',
    2 => 'Lettuce',
    7 => 'Apple'
);

As you can see, the value of the id from the original array is now used as a key for the corresponding name in the new array.


More Posts That You Might Like…


Leave a Reply

Categories

Newsletter

Receive new articles from this blog directly in your inbox!

No spam guaranteed!

Blog at WordPress.com.

%d bloggers like this: