biyobojuji
biyobojuji

Reputation: 43

Remove duplicate array key

Array structure

array:2 [
  0 => array:3 [
    "id" => 15710
    "sale_id" => 6699
    "item_id" => 300
  ]
  1 => array:3 [
    "id" => 15711
    "sale_id" => 6699
    "item_id" => 300
  ]
]

I'm trying to remove the second array if there have same item_id. Therefore, i referred to the array_unique but it seems does not work.

Code

$test = array_unique($model->items->toArray(), SORT_REGULAR);
Debugbar::addMessage($test,'test');

Upvotes: 2

Views: 40

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

Assuming that your array is sorted by id and in case of duplicate you want to preserve the item with the smallest id:

$newArr = [];

foreach(array_reverse($arr) as $v) {
    $newArr[$v['item_id']] = $v;
}

$newArr = array_values($newArr);

demo

Upvotes: 1

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

An old snippet from php.net site that should help you in this case,

function unique_multidim_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
} 

WORKING DEMO: https://3v4l.org/v5k1j

Upvotes: 0

MyLibary
MyLibary

Reputation: 1771

Well, array_unique won't go deep as you wish. You may achieve that by using the following code:

$uniqueItems = array_reduce($array, function($carry, $item){
    if(!key_exists($item['item_id'], $carry)){
        $carry[$item['item_id']] = $item;
    }

    return $carry;
}, []);

If you want to have an indexed array again you may use:

$indexedArray = array_values($uniqueItems);

Upvotes: 1

Related Questions