PHP filter multimensional array by column only where other indexes match

Viewed 29

I have multidimensional array similar to this:

$multidimentionalArray = array (
    array(
    'product' => 'apples',
    'manufacturer' => 'testmanufacturer',
    'price' => '3'
    ), array(
    'product' => 'apples',
    'manufacturer' => 'testmanufacturer',
    'price' => '2'
    ) , array(
    'product' => 'bananas',
    'manufacturer' => 'testmanufacturer',
    'price' => '2'
    )
);

I'm trying to create a function that filter this array so that it would only filter the lowest product price where the product and manufacturer are the same.

So the end result would be:

Array
(
    [0] => Array
        (
            [product] => apples
            [manufacturer] => testmanufacturer
            [price] => 2
        )

    [1] => Array
        (
            [product] => bananas
            [manufacturer] => testmanufacturer
            [price] => 2
        )

)

I've tried the following with no luck:

$price = array_column($multidimentionalArray, 'price'); 

array_multisort($price, SORT_ASC, $multidimentionalArray);

Thanks

1 Answers

You can first find the min and then iterate the array and find the min prices like this:

<?php
$multidimentionalArray = array (
    array(
    'product' => 'apples',
    'manufacturer' => 'testmanufacturer',
    'price' => '3'
    ), array(
    'product' => 'apples',
    'manufacturer' => 'testmanufacturer',
    'price' => '2'
    ) , array(
    'product' => 'bananas',
    'manufacturer' => 'testmanufacturer',
    'price' => '2'
    )
);

$finalArray = [];
$minPrice = min(array_column($multidimentionalArray, 'price'));
foreach ($multidimentionalArray as $value) {
    if ($value['price'] == $minPrice) {
        $finalArray[] = $value;
    }
}

print_r($finalArray);

output

Array
(
    [0] => Array
        (
            [product] => apples
            [manufacturer] => testmanufacturer
            [price] => 2
        )

    [1] => Array
        (
            [product] => bananas
            [manufacturer] => testmanufacturer
            [price] => 2
        )

)
Related