Reputation: 43
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
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);
Upvotes: 1
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
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