Search code examples
phpshufflearray-map

Array_map when elements are shuffled


I have this array (it's just a part of it). 6 = question ID, optionIDs = possible answers.

Array
 (
    [3] => Array
        (
        [0] => 6
        [1] => Array
            (
                [0] => Array
                    (
                        [optionID] => 16
                        [isCorrect] => 0
                    )

                [1] => Array
                    (
                        [optionID] => 14
                        [isCorrect] => 1
                    )

                [2] => Array
                    (
                        [optionID] => 15
                        [isCorrect] => 0
                    )

                [3] => Array
                    (
                        [optionID] => 17
                        [isCorrect] => 0
                    )

            )

    )

[7] => Array
    (
        [0] => 6
        [1] => Array
            (
                [0] => Array
                    (
                        [optionID] => 16
                        [isCorrect] => 0
                    )

                [1] => Array
                    (
                        [optionID] => 15
                        [isCorrect] => 0
                    )

                [2] => Array
                    (
                        [optionID] => 17
                        [isCorrect] => 0
                    )

                [3] => Array
                    (
                        [optionID] => 14
                        [isCorrect] => 1
                    )

            )

    )

)

I'm trying to merge redundant questions (6 and 6) with array_map:

    $unique = array_map('unserialize', array_unique(array_map('serialize', $quizQuestionArray)));

And it works as long as optionIDs are in the same order. But in some cases (like here) they are shuffled (16,14,15,17) (16,15,17,14). Is there a way to keep them shuffled and remove duplicate questions?


Solution

  • array_map-serialize is a pretty crude way to deduplicate an array. You should be using something like this instead:

    $dupeIds = [];
    $array = array_filter($array, function ($item) use (&$dupeIds) {
        $keep = !isset($dupeIds[$item[0]]);
        $dupeIds[$item[0]] = true;
        return $keep;
    });