Skip to content
Advertisement

How to display unique results from an array with two conditions

In $data I have the following values:

Result

JavaScript

I want unique results for id and id_orders. I want 3 out of these 9 results. I have tried this, but it helps on one id_orders condition.

PHP code

JavaScript

Do you know how it can be different to make it work for two?

Advertisement

Answer

You can do it by keeping track of the values that were already used. Disclaimer: this solution will only produce a clear result for cases where the number of unique values for both criteria is the same.

JavaScript

Basically, what’s happening here is that we’re using $usedValues to store all the unique values we’ve already used and comparing against it using in_array. When we iterate through the objects, any object with an id or id_orders that has already been used will be skipped. The pairings will be done in order of appearance in the array.

I’ve gone an extra mile to try and make this code a bit more generic:

JavaScript

In its core, this is the same algorithm, but made dynamic. It allows a variable number of keys to filter on (that’s why they’re passed separately as an argument), so the $usedValues array is created dynamically (using the first element’s keys as its own keys, filled with empty arrays) and all the keys must be compared in loops (hence the separate function to check if an element’s value had already been used).

It could probably be tweaked here or there as I haven’t tested it thoroughly, but should provide satisfactory results for most structures.

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