1

I have multidimensional array looks like that:

Array3: [
    0 => array:2 [
            model_id => 1
            price => 2000
         ]      
    1 => array:2 [
            model_id => 2
            price => 3000
         ]
    2 => array:2 [
            model_id => 1
            price => 1500
         ]
   ]

Now I need to check if value of model_id occurs more than once, if so I need to take this one where price value is lower. In this example I have model_id = 1 twice so I should take second one because have lowest price.

How can I do this? I have tried this methods:

how can I get the duplicate multidimensional array in php

PHP: Check for duplicate values in a multidimensional array

Finding Duplicate Values in Multi-dimensional Array

But I still can't deal with the problem. Resulting array should look like that:

Array2: [
    0 => array:2 [
            model_id => 2
            price => 3000
         ]
    1 => array:2 [
            model_id => 1
            price => 1500
         ]
   ]
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
jakmen
  • 93
  • 10
  • 1
    @Cid I have edited my post – jakmen Jul 01 '19 at 13:48
  • Did you give up??? – AbraCadaver Jul 02 '19 at 18:25
  • @AbraCadaver No, no, I tested the proposed solutions but I haven't implemented any specific of it yet. I'm ashamed to admit but I'm afraid solution I was looking for wont be the best solution in my case. I will try to deal with the problem with proposed array filtering but I think i will need diffrent way to solve it – jakmen Jul 03 '19 at 10:40

6 Answers6

2

You can sort descending by price, then extract and index on model_id so the last one (lowest price of each model_id index) will overwrite the others:

array_multisort(array_column($array, 'price'), SORT_DESC, $array);
$result = array_column($array, null, 'model_id');
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

Simple foreach should do it as:

foreach($arr as $e) {
    if (isset($res[$e["model_id"]]))
        $res[$e["model_id"]]["price"] = min($res[$e["model_id"]]["price"], $e["price"]);
    else $res[$e["model_id"]] = $e;
}

Live example: 3v4l

dWinder
  • 11,597
  • 3
  • 24
  • 39
1

You can take advantage of associative array keys to enforce uniqueness and compare prices:

<?php
// Our data
$array = [
    [ 'model_id' => 1, 'price' => 2000 ],
    [ 'model_id' => 2, 'price' => 3000 ],
    [ 'model_id' => 1, 'price' => 1500 ]
];

// Store the final result
$result = [];

// Loop the data
foreach( $array as $v )
{
    // If this model_id has not been encountered or if the price is lower than what's stored then make it the new price
    if( !isset( $output[ $v[ 'model_id' ] ] ) || $v[ 'price' ] < $output[ $v[ 'model_id' ] ][ 'price' ] )
    {
        $output[ $v[ 'model_id' ] ] = $v;
    }
}

// Get rid of the unique keys
$output = array_values( $output );

print_r( $output );

Outputs:

Array
(
    [0] => Array
        (
            [model_id] => 1
            [price] => 1500
        )

    [1] => Array
        (
            [model_id] => 2
            [price] => 3000
        )

)
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
0

You can group by them for model_id than use min function

$groupByModelId = [];
foreach($a as $v){
  $groupByModelId[$v['model_id']][] = $v['price'];
}
$searchModelId = 1;
echo min($groupByModelId[$searchModelId]);

Working DEMO

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

Here is one more method,

function array_column1($input, $column_key = null, $index_key = null)
{
    $result = [];
    $i      = 0;
    foreach ($input as $v) {
        $k            = $index_key === null || !isset($v[$index_key]) ? $i++ : $v[$index_key];
        // fetching all the values for model id
        $result[$k][] = $column_key === null ? $v : (isset($v[$column_key]) ? $v[$column_key] : null);
    }
    // fetching minimum for every model_id
    $result = array_map("min", $result);
    return $result;
}
$temp = array_column1($arr, 'price', 'model_id');

Demo.

I used this function from official php doc.

Rahul
  • 18,271
  • 7
  • 41
  • 60
0

You can use usort array function for get first min value records, then use temp array and run foreach function for remove duplicate records.

Below code is working fine for me.

<?php


$arr = array(
        [   
            'model_id' => 1,
            'price' => 2000
        ],
        [
            'model_id' => 2,
            'price' => 3000
        ],
        [
            'model_id' => 1,
            'price' => 1500
        ]
    );

    usort($arr, function ($a, $b) {
        return $a['price'] - $b['price'];
    });

    $input = $arr;
    $temp  = array();
    $keys  = array();

    foreach ( $input as $key => $data ) {
        unset($data['price']);
        if ( !in_array($data, $temp) ) {
            $temp[]     = $data;
            $keys[$key] = true;
        }
    }

    $output = array_intersect_key($input, $keys);

    print_r($output);