合并两个数组,从中删除重复键

时间:2015-04-11 09:23:35

标签: php arrays

我有两个数组。这些是:

First Array:

$arr1[0] = 'Programs';
$arr1[1] = 'Levels';
$arr1[2] = 'Presenters';
$arr1[3] = 'Levels';

第二阵列:

$arr2[0] = 'Art';
$arr2[1] = 'Primary';
$arr2[2] = 'Kristine Ballard';
$arr2[3] = 'Secondary';

我想得到这样的输出:

Programs = Art
Levels = Primary, Secondary
Presenters = Kristine Ballard

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

如果有多个键值,您将创建一个多维数组:

$arr1[0] = 'Programs';
$arr1[1] = 'Levels';
$arr1[2] = 'Presenters';
$arr1[3] = 'Levels';

$arr2[0] = 'Art';
$arr2[1] = 'Primary';
$arr2[2] = 'Kristine Ballard';
$arr2[3] = 'Secondary';

$newArray = array();

foreach($arr1 as $index => $key) {
    $newArray[$key][] = $arr2[$index];
}

print_r($newArray);

输出:

Array
(
    [Programs] => Array
        (
            [0] => Art
        )

    [Levels] => Array
        (
            [0] => Primary
            [1] => Secondary
        )

    [Presenters] => Array
        (
            [0] => Kristine Ballard
        )

)

答案 1 :(得分:0)

$arr1[0] = 'Programs';
$arr1[1] = 'Levels';
$arr1[2] = 'Presenters';
$arr1[3] = 'Levels';

$arr2[0] = 'Art';
$arr2[1] = 'Primary';
$arr2[2] = 'Kristine Ballard';
$arr2[3] = 'Secondary';


$newArray = [];
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($arr1));
$mi->attachIterator(new ArrayIterator($arr2));
foreach($mi as list($key, $value)) {
    $newArray[$key][] = $value;
}
var_dump($newArray);

请注意,使用带有list()的foreach()需要PHP> = 5.5.0

对于早期版本的PHP,以下内容将起作用:

$newArray = [];
$mi = new MultipleIterator(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC);
$mi->attachIterator(new ArrayIterator($arr1), 'key');
$mi->attachIterator(new ArrayIterator($arr2), 'value');
foreach($mi as $details) {
    extract($details);    
    $newArray[$key][] = $value;
}
var_dump($newArray);

答案 2 :(得分:0)

我自己得到了另一个解决方案,这是有效的。我刚刚在下面发布了它,以帮助其他人看到这个帖子。这是我的代码:

$arr1[0] = 'Programs';
$arr1[1] = 'Levels';
$arr1[2] = 'Presenters';
$arr1[3] = 'Levels';

$arr2[0] = 'Art';
$arr2[1] = 'Primary';
$arr2[2] = 'Kristine Ballard';
$arr2[3] = 'Secondary';

$new_arr1 = array_values(array_unique($arr1));

for ($i = 0; $i < count($new_arr1); $i++)
{
    $var = 0;
    echo $new_arr1[$i]. ': ';
    for ($j = 0; $j < count($arr1); $j++)
    {
        if($new_arr1[$i] == $arr1[$j])
        {
            if($var == 0)
            {
                echo $arr2[$j];
            }
            else
            {
                echo ', ' . $arr2[$j];
            }
            $var++;
        }
    }
    echo '<br>';

}