如何检查此数组中的唯一键和值

时间:2014-11-20 12:18:18

标签: php multidimensional-array

Array ( 
       [0] => Array ( [2] => 3 ) 
       [1] => Array ( [12] => 32 ) 
       [2] => Array ( [2] => 3 ) 
       [3] => Array ( [24] => 42 ) 
);

如何将输出作为唯一键值。我需要删除重复的值。 我需要像这样的o / p

Array ( 
       [0] => Array ( [2] => 3 ) 
       [1] => Array ( [12] => 32 ) 
       [2] => Array ( [24] => 42 ) 
);

5 个答案:

答案 0 :(得分:1)

array_reduce可能是为此目的而设计的:

$a = [ [ 2 => 3 ], [ 3 => 4 ], [ 3 => 15 ], [ 2 => 3 ] ];
array_reduce($a, function($memo, $el) { 
  if(false === array_search($el, $memo)) array_push($memo, $el); 
  return $memo; 
}, array())

#⇒ array(3) {
#  [0] =>
#  array(1) {
#    [2] =>
#    int(3)
#  }
#  [1] =>
#  array(1) {
#    [3] =>
#    int(4)
#  }
#  [2] =>
#  array(1) {
#    [3] =>
#    int(15)
#  }
#}

答案 1 :(得分:0)

试试这个:

$array = array(
    array(2 => 3),
    array(12 => 32),
    array(2 => 3),
    array(24 => 32)
);

echo 'before array_unique_multi:' . "\n";
print_r($array);

echo 'after array_unique_multi:' . "\n";
print_r(array_unique_multi($array));

function array_unique_multi($array)
{
    $hashAry = array();
    foreach($array as $k=>$v){
        $hash = md5(serialize($v));
        if(in_array($hash, $hashAry)) unset($array[$k]);
        else $hashAry[]=$hash;
    }
    $array = array_values($array);
    return $array;
}

输出:

before array_unique_multi:
Array
(
    [0] => Array
        (
            [2] => 3
        )

    [1] => Array
        (
            [12] => 32
        )

    [2] => Array
        (
            [2] => 3
        )

    [3] => Array
        (
            [24] => 32
        )

)
after array_unique_multi:
Array
(
    [0] => Array
        (
            [2] => 3
        )

    [1] => Array
        (
            [12] => 32
        )

    [2] => Array
        (
            [24] => 32
        )

)

答案 2 :(得分:-1)

您可以使用array_unique功能。
http://php.net/manual/fr/function.array-unique.php

foreach ($myMultiArray as $index => $doublonArray) {
    $myMultiArray[$index] = array_unique($doublonArray);
}

答案 3 :(得分:-1)

使用它。这将在新数组中存储所有不同的键/值对。

$test = array(
    array(2 => 3),
    array(12 => 32),
    array(2 => 3),
    array(24 => 42)
);

$tmpArray = array();
$newArray = array();

foreach ($test as $elements) {
    foreach ($elements as $key => $val) {
        if (!array_key_exists($key, $tmpArray) || $tmpArray[$key] !== $val) {
            $tmpArray[$key] = $val;
        }
    }
}
foreach ($tmpArray as $key => $val) {
    $newArray[] = array($key => $val);
}

var_dump($newArray);

输出:

array
  0 => 
    array
      2 => int 3
  1 => 
    array
      12 => int 32
  2 => 
    array
        24 => int 42

答案 4 :(得分:-1)

$check_arr = Array ( 
  [0] => Array ( [13] => 1 )
  [1] => Array ( [13] => 3 ) 
  [2] => Array ( [13] => 1 ) 
  [3] => Array ( [10] => 3 ) 
) ;

print_r(array_unique($check_arr));

这是我的结果。

Array ( [0] => Array ( [13] => 1 ) );