如何将数组合并到自身?

时间:2011-12-01 00:08:30

标签: php arrays multidimensional-array

如果我print_r($pieces);我得到:

Array
(
    [0] => Albany, NY
)
Array
(
    [0] => Albany, NY
    [1] => Albuquerque, NM
    [2] => Atlanta, GA
    [3] => Augusta, ME
    [4] => Billings, MT
    [5] => Baltimore, MD
)
Array
(
    [0] => Albany, NY
    [1] => Albuquerque, NM
    [2] => Atlanta, GA
    [3] => Augusta, ME
    [4] => Billings, MT
    [5] => Birmingham, AL
    [6] => Boise, ID
    [7] => Boston, MA
    [8] => Buffalo, NY
    [9] => Charleston, SC
    [10] => Charleston, WV
)
.....

我需要做的是组合这些数组以获得唯一值。 首先,我需要将其拆分为多个数组,然后使用array_combine,但它似乎不起作用。

2 个答案:

答案 0 :(得分:6)

$unique = array();
foreach ($pieces as $piece) {
    $unique = array_merge($unique, $piece);
}
$unique = array_unique($unique);

或者,如果您使用的是PHP 5.3 +:

array_unique(array_reduce($pieces, function ($a, $p) { return array_merge($a, $p); }, array()));

答案 1 :(得分:0)

Bouni的评论有最好的答案:

array_unique(array_reduce($ pieces,'array_merge',[]));