3

I'm not sure the title really gets across what I'm asking, so here's what I'm trying to do:

I have an array of arrays with four integer elements each, ie.

Array(Array(1,2,3,4), Array(4,2,3,1), Array(18,3,22,9), Array(23, 12, 33, 55))

I basically need to remove one of the two arrays that have the same values in any order, like indices 0 and 1 in the example above.

I can do this pretty easily when there are only two elements to check, using the best answer code in this question.

My multidimensional array can have 1-10 arrays at any given time, so I can't seem to figure out the best way to process a structure like that and remove arrays that have the same numbers in any order.

Thanks so much!

1 Answer 1

4

I've been thinking about this, and I think using a well designed closure with array_filter might be the way I'd go about this:

$matches = array();
$array = array_filter($array, function($ar) use (&$matches) {
    sort($ar);
    if(in_array($ar, $matches)) {
        return false;
    }
    $matches[] = $ar;
    return true;
});

See here for an example: http://ideone.com/Zl7tlR

Edit: $array will be your final result, ignore $matches as it's just used during the filter closure.

Sign up to request clarification or add additional context in comments.

6 Comments

That looked like a great answer but I've just ran this and got the same array back?
The ideone example appears to work. Can you show me what input you gave it?
Ah sorry. I must of copied it wrong, I had $ar where I should have had $array.
Great answer, but I seem to be getting matches that aren't in the original array. $array = [[11,18,22,43],[42,21,38,23],[28,33,17,32],[12,25,38,22],[11,22,43,18],[12,14,17,19],[34,23,11,32],[21,33,42,45],[1,2,8,23],[8,2,1,23]] $matches = [[11,18,22,43],[21,23,38,42],[17,28,32,33],[12,22,25,38],[12,14,17,19],[11,23,32,34],[21,33,42,45],[1,2,8,23]] I've worked up something that seems to give me the desired result, though I'm sure it's inefficient. I'll post it as an answer shortly.
I didn't note in my answer, but $array contains the result of the filter. $matches is just used for the filter. It will actually end up containing all the matches values as well except they will be sorted.
|

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.