0

我有以下多维数组:

<?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

4 回答 4

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),
);
于 2012-07-04T14:41:08.130 回答
0

这将删除重复的数组:

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

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

于 2012-07-04T14:42:31.207 回答
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),
);

?

于 2012-07-05T10:39:29.580 回答
0

您必须自己做一些foreach循环并重新组装数组。也可以查看 PHP 的array_unique()

于 2012-07-04T14:38:51.750 回答