Search code examples
phpmultidimensional-arrayarray-filterarray-columnarray-combine

php multidimensional array get prices in specific category


[0] => Array
    (
        [id] => 004002718
        [price] => 5.00
        [category] => x
    )

[1] => Array
    (
        [id] => 030285882
        [price] => 8.99
        [category] => y

    )

[2] => Array
    (
        [id] => 040685111
        [price] => 19.99
        [category] => x

    )

How can I get the prices for all items in a specific category? So for example for category value 'x' I would like [5.00, 19,99] returned.

This way I can easily extract the max, min and average price in each category (which is my goal)

I've tried using array_column, array_keys and array_filter but couldn't get it to work using these functions

I see this question was marked as duplicate, but the 'duplicate' just refers to looping over an array. Based on the usefulness of the answers in this thread I'm sure this example could help others as well. Specifically I learned about the use of 'function' and 'use' in combination with array_filter


Solution

  • You can try using array_filter() and array_column().

    • Using array_filter() filter the array of specific category
    • using array_column() just get the price column as an array.

    Example code:

    $filter_category = 'x';
    $filtered_data = array_filter($array, function($item) use ($filter_category) { return $item['category'] === $filter_category; });
    $filtered_data = array_column($filtered_data, 'price');
    

    Alternatively you can try with array_reduce().

    Example code:

    $filter_category = 'x';
    $filtered_data = array_reduce($arr, function($old, $new) use ($filter_category) {
        if ($new['category'] === $filter_category) {
            $old[] = $new['price'];
        }
        return $old;
    }, []);