array_unique()不起作用-与nonArray混合

时间:2019-05-31 19:13:19

标签: php arrays

我在从数组中删除重复项时遇到了一些麻烦。这是我的代码:

$invoice_numbers = array_unique($invoice_numbers, SORT_REGULAR);
return $response->withJson($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"
    }

现在我知道这不适用于多维数组。但我也尝试过此操作:(请注意,键nr.9不是数组,然后会引发错误)

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

有人可以帮助我在数组中创建唯一值吗?谢谢

  

这是错误:警告:array_merge():参数8不是   数组

结果为“空”

1 个答案:

答案 0 :(得分:1)

此代码使用array_reduce()遍历初始数组并合并各个组件。如您所见,虽然有些不是数组-所以我使用is_array($element)?$element:[$element],如果不是数组,它将变成数组...

$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));