A useful way to create new WordPress arrays

Let say you have a set of data stored in an array and you want to isolate or create a new array with certain data.

There is a powerful function called wp_list_pluck() and wp_list_filter() that can be used for such tasks with any sort of datasets.

For example consider the following array:


$vehicles = array(
    array(
        'id' => 1,
        'type' => 'car',
        'color' => 'red',
    ),
    array(
        'id' => 2,
        'type' => 'car',
        'color' => 'blue',
    ),
    array(
        'id' => 3,
        'type' => 'car',
        'color' => 'red',
    ),
    array(
        'id' => 4,
        'type' => 'truck',
        'color' => 'green',
    ),
    array(
        'id' => 5,
        'type' => 'bike',
        'color' => 'blue',
    ),
);

First of all we can use wp_list_pluck() with 2 parameters, the array to pluck and the key to be plucked. So to create another array that contains just the key for the “type” we would do the following:

$new_array = wp_list_pluck($vehicles, 'type');
// would produce the following
// array('car', 'car', 'car', 'truck', 'bike');

The same could be done to collate the id’s for later loops:

$new_array = wp_list_pluck($vehicles, 'id');
// would produce the following
// array('1', '2', '3', '4', '5');

wp_list_filter() is another useful and powerful function that can be used to further refine your new array, say for instance you’d like to create a new array with just cars that are red, this is how you can go about it:

$filter_to_use = array('type' => 'car', 'color' => 'red');
$red_cars = wp_list_filter($vehicles, $filter_to_use);
// this would end up creating an array like so
// array(
//    array(
//        'id' => 1,
//        'type' => 'car',
//        'color' => 'red',
//    ),
//    array(
//        'id' => 3,
//        'type' => 'car',
//        'color' => 'red',
//    )
//);

Both of these functions are very useful when is comes to creating new arrays.

About

A geek who likes to cook with wp ingredients!

Leave a Reply

Your email address will not be published. Required fields are marked *