-2
[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

dean2020
  • 645
  • 2
  • 8
  • 25

2 Answers2

3

You can just use foreach to get it,

    $prices = [];
    $category = "x";
    foreach($arrays as $array){
        if($array["category"] == $category){
            $prices[] = $array["price"];
        }
    }
    var_dump($prices);
LF00
  • 27,015
  • 29
  • 156
  • 295
  • Thanks Kris, this works also but since I was trying to solve this with array_filter/array_column I accepted the other answer – dean2020 Sep 05 '19 at 12:14
2

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;
}, []);
MH2K9
  • 11,951
  • 7
  • 32
  • 49
  • I'm not a fan of the 3rd line in your array_reduce() example, what's wrong with using an `if...`, IMHO an `if` is much more standard and clearer. – Nigel Ren Sep 05 '19 at 12:10
  • @NigelRen I'm agree with you but for making it shorten often I do it in my codes. – MH2K9 Sep 05 '19 at 12:13
  • If it was a choice between shorter and clearer - I would always stick with being clearer, after all your code may be around for some time and not everyone understands how some of these shortcuts work. – Nigel Ren Sep 05 '19 at 12:15
  • Yes! you are right. I made it clean. Thanks geek :) – MH2K9 Sep 05 '19 at 12:17