This is my array:

[0] => Array
    (
        [0] => SupSKU
        [1] => MfrSKU
        [2] => Cost
    )

[1] => Array
    (
        [0] => A
        [1] => 11742-4
        [2] => 47.25
    )

[2] => Array
    (
        [0] => B
        [1] => 11742-4
        [2] => 283.5
    )

[3] => Array
    (
        [0] => C
        [1] => 0904101
        [2] => 995
    )

I want to find duplicates values in Mfrsku value, in this example that is 11742-4, then compare their prices, and save bigger price SupSku value.
So my output will be

$final_output => Array ( 
  [0] => B
)

I tried with this but this only retun empty array

array_unique(array_diff_assoc($ar,array_unique($ar)));

Recommended Answers

All 2 Replies

So far the Code Snippet Repository is for you to show your completed and working code. Maybe a moderator can change your post type?

commented: done +16

You can skin this particular cat in many ways. here are 2 examples, neither of which I've given much thought to - so there's probably a few better ways out there. Anyway...

<?php
$inputArray =
    [
        [
            'SupSKU',
            'MfrSKU',
            'Cost'
        ],
        [
            'A',
            '11742-4',
            47.25
        ],
        [
            'B',
            '11742-4',
            283.5
            ],
        [
            'C',
            '0904101',
            995
        ]

    ];

//Using array functions and a reduced loop
function getSupSKU( $source, $SKU )
{
    $valArray = array_filter( $source, function ($var) use ($SKU) {
        return ($var[1] == $SKU);
    }); //filter array to just contain 11742-4
    $maxCost = max( array_column( $valArray, 2 ) ); //get max cost
    foreach($valArray as $item) {
        if ($item[2] === $maxCost) return $item[0]; //return FIRST max hit
    }
    return false;
}

//Using a big loop
function getSupSKU2( $source, $SKU )
{
    $output = false;
    $maxCost = 0;
    foreach($source as $item) {
        if ($SKU === $item[1] && $item[2] > $maxCost){
            $maxCost = $item[2];
            $output = $item[0];
        }
    }
    return $output;
}

$SKU = '11742-4';

array_shift( $inputArray ); //get rid of labels

echo getSupSKU( $inputArray, $SKU );

echo getSupSKU2( $inputArray, $SKU );

//EDIT - try some PHP execution timers on different length arrays - the straight loop consistently outperformed the array function script by around a factor of 3 in simple tests.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.