Skip to content
Advertisement

PHP – How To Grouping if value same in array

This my array example

JavaScript

And i want to group if product value same, like this,

JavaScript

Advertisement

Answer

It makes no sense to retain the first level ids since you are arbitrarily trashing some of the first level ids (damaging the relationships) during the merging process.

Instead I recommend that you only isolate the data that is accurately related.

If this output does not serve your needs, then I’ll ask for further question clarification.

By assigning temporary keys to your output array, the output array also acts as a lookup array by which you can swiftly check for uniqueness. The “null coalescing operator” (??) sets a fallback value of 0 when an id is encountered for the first time — this prevents generating any warnings regarding undeclared keys.

Code: (Demo)

JavaScript

Output:

JavaScript

If you insist of the desired output in your question, then it can be as simple and efficient as this…

Code: (Demo)

JavaScript

Output:

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