获取$ key的唯一数组

时间:2015-02-26 06:44:19

标签: php arrays array-unique

我有以下代码:

$keys = array('2', '2', '6', '10', '10', '10', '13', '13', '13', '13', '13', '13', '13', '13', '13', '13', '15', '16', '18', '18', '18', '18', );
$values = array('1712', '1712', '1977', '231', '245', '245', '11', '11', '1121', '1121', '1121', '141', '144', '144', '145', '16', '1980', '153', '153', '171', '171', '183');
$result = array();
foreach ($keys as $i => $k){
    $result[$k][] = $values[$i];
}
print_r($result);

哪个输出:

Array (
    [2] => Array ([0] => 1712 [1] => 1712 )
    [6] => Array ([0] => 1977)
    [10] => Array ([0] => 231 [1] => 245 [2] => 245)
    [13] => Array ([0] => 11 [1] => 11 [2] => 1121 [3] => 1121 [4] => 1121 [5] => 141 [6] => 144 [7] => 144 [8] => 145 [9] => 16)
    [15] => Array ([0] => 1980)
    [16] => Array ([0] => 153)
    [18] => Array ([0] => 153 [1] => 171 [2] => 171 [3] => 183)
)

我希望“子数组”对每个键都是唯一的,如下面的输出 - (唯一数组):

Array (
    [2] => Array ([0] => 1712)
    [6] => Array ([0] => 1977)
    [10] => Array ([0] => 231 [1] => 245)
    [13] => Array ([0] => 11 [1] => 1121 [2] => 141  [3] => 144 [4] => 145 [5] => 16)
    [15] => Array ([0] => 1980)
    [16] => Array ([0] => 153)
    [18] => Array ([0] => 153 [1] => 171 [2] => 183)
)

3 个答案:

答案 0 :(得分:3)

通过array_unique

使用array_map
$result = array_map('array_unique', $result);

答案 1 :(得分:0)

在每个子阵列上调用array_unique()函数:

foreach ($result as $key => $subArray) {
    $result[$key] = array_unique($subArray);
}

答案 2 :(得分:0)

构建子阵列后,您需要从子阵列中删除重复项,例如:

  foreach ($result as $ind => $sub_arr)
  {
      $result[$ind] = array_unique($sub_arr);
  }

试试这个:     

 $keys = array('2', '2', '6', '10', '10', '10', '13', '13', '13', '13', '13', '13', '13', '13', '13', '13', '15', '16', '18', '18', '18', '18' );

 $values = array('1712', '1712', '1977', '231', '245', '245', '11', '11', '1121', '1121', '1121', '141', '144', '144', '145', '16', '1980', '153', '153', '171', '171', '183');
$result = array();
foreach ($keys as $i => $k){
    $result[$k][] = $values[$i];

}

foreach ($result as $ind => $sub_arr)
{
    $result[$ind] = array_unique($sub_arr);
}

print_r($result);
?>

输出:

Array (
    [2] => Array ([0] => 1712 [1] => 1712 )
    [6] => Array ([0] => 1977)
    [10] => Array ([0] => 231 [1] => 245 [2] => 245)
    [13] => Array ([0] => 11 [1] => 11 [2] => 1121 [3] => 1121 [4] => 1121 [5] => 141 [6] => 144 [7] => 144 [8] => 145 [9] => 16)
    [15] => Array ([0] => 1980)
    [16] => Array ([0] => 153)
    [18] => Array ([0] => 153 [1] => 171 [2] => 171 [3] => 183)
)