Skip to content
Advertisement

PHP array merging, ignore certain duplicated keys and let them be included in the inner created arrays

I’m merging together arrays with the same set inner array name, changing the key value to the order number then creating further inner arrays for items that are not duplicated with this code…

JavaScript

This turns..

JavaScript

into

JavaScript

So because qty = 1 is the same its getting filtered out, when what I need is..

JavaScript

How can I exclude certain ones from the “remove duplicates” part so they are repeated in an inner-array as in my last example? This is needed as they are directly linked to other items with an inner array, so if for example the item1 inner array now has 6 items the qty now needs to also have all 6 items in the inner array, even if they are the same.

Advertisement

Answer

Your current code is good for two cases:

  1. Reading all data as is, without modification
  2. Reading all data and performing a universal modification

Since what you need is a conditional modification, it seems like you would be better off creating the structure of the array manually. Doing so would add another benefit: code clarity. You should always strive for descriptive code, so building your array with descriptive associative keys would make the intent of the code clearer.

Proposed solution based off the example data (rough sketch that you should tailor to your specific needs):

JavaScript

Now all the items of your order are neatly stored as subarrays, each containing only data specific to that item, which makes it really easy to iterate:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement