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.

2
  • 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. Commented Jan 30, 2019 at 8:59
  • You obviously select all products from database, but instead you should select distinct productTypes from products table. Commented Jan 30, 2019 at 9:01

2 Answers 2

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;
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I this seems to work well and means I do not have as many variables. Thank you :)
-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"));

3 Comments

I think it will not work such a way with some levels of objects
@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.
if I undestand the structure right - sandbox.onlinephpfunctions.com/code/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.