如何删除多维数组中特定键的重复值?

时间:2012-07-04 14:34:20

标签: php arrays

我有以下多维数组:

<?php 
$array = array(
array('first' => 1, 'second' => 1),
array('first' => 1, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1),
array('first' => 3, 'second' => 1),
array('first' => 3, 'second' => 1));

如何删除重复的first值?同时保留重复的second值。

处理后的数组应为:

array(
array('first' => 1, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1));

请参阅:http://codepad.org/tMh28KMf

4 个答案:

答案 0 :(得分:1)

代码:

$array = array(
    array('first' => 1, 'second' => 1),
    array('first' => 1, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
    array('first' => 3, 'second' => 1)
);

$temp = array();
$new = array();

foreach($array as $value)
{
    if(!in_array($value['first'],$temp))
    {
        $temp[] = $value['first'];
        $new[] = $value;
    } 
}

现在$new包含以下内容:

array(
    array('first' => 1, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
);

答案 1 :(得分:0)

您必须执行一些foreach循环并自行重新组装阵列。查看PHP的array_unique()

答案 2 :(得分:0)

这将删除重复的数组:

$array = array_map('unserialize', array_unique(array_map('serialize', $array)));

密钥仍然相同,因此您可能需要修复它们。

答案 3 :(得分:0)

如果数组是这样的话

$array = array(
    array('first' => 1, 'second' => 1),
    array('first' => 1, 'second' => 1),
    array('first' => 1, 'second' => 12),
    array('first' => 2, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
    array('first' => 3, 'second' => 1)
);

$temp = array();
$new = array();

您希望新数组$ new包含以下内容:

array(
    array('first' => 1, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
);

array(
    array('first' => 1, 'second' => 1),
    array('first' => 1, 'second' => 12),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
);