0

I am having some trouble with removing duplicates from an Array. This is my code:

$invoice_numbers = array_unique($invoice_numbers, SORT_REGULAR);
return $response->withJson($invoice_numbers);

$invoice_numbers:

 {
    "0": [
    "8250",
    "8436",
    "8584",
    "8708",
    "8838",
    "9076",
    "9125",
    "9186"
    ],
    "1": [
    "8250",
    "8436",
    "8584",
    "8708",
    "8838",
    "9076",
    "9125",
    "9186",
    "9895"
    ],
    "3": [
    "9758",
    "9799",
    "10168",
    "10227",
    "10465",
    "10517",
    "10655",
    "10729",
    "10758"
    ],
    "4": [
    "9798",
    "10226",
    "10516"
    ],
    "5": [
    "10926",
    "11246",
    "11591",
    "11790",
    "11791",
    "11802",
    "11803"
    ],
    "6": [
    "10897",
    "11002",
    "11142",
    "11277",
    "11279",
    "11345",
    "11458",
    "11478",
    "11492",
    "11498",
    "11501",
    "11526",
    "11676",
    "11761",
    "11780",
    "11781",
    "11833",
    "11946",
    "12031",
    "12048",
    "12119"
    ],
    "7": "12201",
    "8": [
    "11214",
    "11502",
    "11538",
    "11677",
    "11834",
    "12120"
    ],
    "9": "11643"
    }

Now i know that this does not work with multidimensional array. But i also tried this: (Note that key nr.9 is not an array then it throws an error)

$invoice_numbers = array_unique(call_user_func_array('array_merge', $invoice_numbers), SORT_REGULAR);
return $response->withJson($invoice_numbers);

Can someone help me with creating a unique value in array? Thanks

This is the error: Warning: array_merge(): Argument #8 is not an array

And result is "null"

1 Answer 1

1

This code uses array_reduce() to iterate over the initial array and merge the individual components. As you can see though some aren't arrays - so I use is_array($element)?$element:[$element] which if is isn't an array, it makes it an array...

$invoice_numbers = array_reduce($invoice_numbers, function ($list, $element) {
    return array_merge($list, is_array($element)?$element:[$element]);
}, []);

return $response->withJson(array_unique($invoice_numbers, SORT_REGULAR));
Sign up to request clarification or add additional context in comments.

Comments

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.