I'm not sure why this is getting negative reputation. The suggested duplicate questions only deal with identical items in the array. I'm looking for arrays that have the same value for just one item in that array.
Here is my question:
I need to remove items from a multidimensional array based on the value of one of the keys. Here's a sample of the array. The actual array has 3,000 items.
Array
(
[0] => Array
(
[ID] => 1553
[Title] => Red Mini Dress
[Size] => 8
[Availability] => In stock
)
[1] => Array
(
[ID] => 1554
[Title] => Red Mini Dress
[Size] => 10
[Availability] => Out of stock
)
[2] => Array
(
[ID] => 1555
[Title] => Red Mini Dress
[Size] => 12
[Availability] => In stock
)
[3] => Array
(
[ID] => 2430
[Title] => Black Cotton Trousers
[Size] => 14
[Availability] => In stock
)
...
)
So you can see that some items, like "Red Mini Dress", are listed several times. This is because there is an entry for every size of that item.
You can also see that sizes 8 and 12 of "Red Mini Dress" are in stock, but not size 10.
Now, I need to reduce the array to show just one entry for each product. And the value of Availability
should be In stock
unless all sizes are out of stock.
So, for the above example, there should be only one entry for "Red Mini Dress", and it should be In stock
.
Edit
So far I've tried using this method, which sorts the array based on the size of the ID:
function reduce_products($items) {
$reduced = array();
for($i = 0; $i < sizeof($items); $i++) {
if (!array_key_exists($items[$i]['id'], $reduced) || $reduced[$items[$i]['id']]['title'] > $items[$i]['title'])
$reduced[$items[$i]['id']] = $items[$i];
}
return $reduced;
}
The code is adapted from Removing duplicate values in Multi-Dimensional Array?
But that doesn't remove any values.