0

I have a multidimensional array, consisting of products. Each sub-array has a product type. The productType is is in an array inside the Product array, such that;

 0 => product [
  productType [
  id: 2
  ]
 ]
 1 => product [
  productType [
  id: 1
  ]
 ]
 2 => product [
  productType [
  id: 2
  ]
 ]
]

I need to remove an entire array element, if the id already exists, in this example, I would need to remove EITHER array[0] or array[2], it doesn't matter as I only need the productType[id] to populate the box.

I have made a loop that creates an array of the ID's that already exist, but it involves making 2 new arrays:

    //This works but seems a bit inefficient
    $productFinal = [];
    $ids = [];
    foreach ($products as $product) {
        if (!in_array($product->getproductType()->getid(), $ids)) {
            $productFinal[] = $product;
        }
        $ids[] = $product->getproductType()->getid();
    }

I get the results I want, however I am sure that there is a more efficient way to do this, ideally using an inbuilt php function.

  • 1
    Please show a proper example array, preferable already as copy&paste-able PHP code. `0 => product [` doesn’t seem to make much sense, you either have a numeric key, or a string one. – 04FS Jan 30 '19 at 08:59
  • You obviously select __all products__ from database, but instead you should select distinct productTypes from products table. – u_mulder Jan 30 '19 at 09:01

2 Answers2

0

If you also get the key of each element, you could remove the element if necessary inside the foreach-loop:

$ids = [];
foreach ($products as $key => $product {
   $id = $product->getproductType()->getid();
   if (in_array($id, $ids)) {
      unset($product[$key];
   } else {
      $ids[] = $id;
   }
}
Gerriet
  • 1,302
  • 14
  • 20
-1

There is no need for a loop, you can use array_column to make the array associative, which will remove any duplicates.
Then use array_values to make the array indexed again.

$arr = array_values(array_column($arr, Null, "id"));
Andreas
  • 23,610
  • 6
  • 30
  • 62
  • 1
    I think it will not work such a way with some levels of objects – splash58 Jan 30 '19 at 09:14
  • @splash58 it has worked every time I have tried it. Maybe there is some arrays it won't work on, but I have not come across any yet. – Andreas Jan 30 '19 at 09:16
  • 1
    if I undestand the structure right - http://sandbox.onlinephpfunctions.com/code/a522cff3f53a14fbf53c69c7483f65508dacfd3a – splash58 Jan 30 '19 at 09:22