如何防止array_push中的重复键

时间:2013-05-12 13:10:40

标签: php arrays key array-push

我有2个2D阵列,我怎样才能获得唯一的密钥而只推送它们?例如:

$array = json_decode('[{"7654321":1368356071},{"1234567":1368356071}]',true);
$array2 = array(array(1234567 => time()), array(7654321 => time()), array(2345678 => time()));
//array_push($array, $array2[2]); 

- 如何在此示例中动态获取$ array2 [2]等唯一键?

2 个答案:

答案 0 :(得分:3)

为什么不在php中使用array_unique()函数? http://php.net/manual/ru/function.array-unique.php

答案 1 :(得分:1)

你的意思是,你想推入另一个数组(让我们说在$ keys_unique中),只有前两个数组中只有一个存在的键,但两个数组中都不存在?

试试这个:

$arrays_mixed = array(  //your $array and $array2; you can put as many arrays as you want here
     json_decode('[{"7654321":1368356071},{"1234567":1368356071}]',true)
    ,array(array(1234567 => time()), array(7654321 => time()), array(2345678 => time()))
);

//begin getting all keys
$arrays_keys = array(); //will hold all keys from arrays_mixed
$keys_unique = array(); //will hold all unique keys out of arrays_key
for($x=0;$x<count($arrays_mixed);$x++){
    $arrays_keys[$x] = array(); //prepares a "keys holder"
    $toflatten = $arrays_mixed[$x];
    $c1 = 0;
    do{
        $arrmixed = array();
        $arrclean = array();
        foreach($toflatten as $a){
            $arrmixed = $this->keys_finder($a,1);
            $arrclean[$c1] = $this->keys_finder($a,2);
            $c1++;
        }
        $toflatten = $arrmixed;
    }while(is_array($toflatten));
    for($c2=0;$c2<$c1;$c2++)
        foreach($arrclean[$c2] as $ac)
            array_push($arrays_keys[$x],$ac);
}//end geting all keys

//begin finding unique keys
foreach($arrays_keys as $ak)
    foreach($ak as $add)
        $keys_unique = $this->unique_inserter($arrays_keys,$keys_unique,$add);
//end finding unique keys

以下是您需要的功能

function unique_inserter($arrays_keys,$keys_unique,$add){
    $detector = 0;  //detects how many arrays contain a value
    foreach($arrays_keys as $ak)
        if(in_array($add,$ak))
            $detector++;
    if($detector<2) //if value is found in one array only
        array_push($keys_unique,$add);
    return $keys_unique;
}
function keys_finder($array,$return){
    $arrmixed = array();
    $arrclean = array();
    foreach($array as $key=>$a)
        if(is_array($a))
            foreach($a as $aa)
                array_push($arrmixed,$aa);
        else
            array_push($arrclean,$key);
    switch($return){
        case 1:
            return (count($arrmixed)==0)?'':$arrmixed;
            break;
        case 2:
            return $arrclean;
            break;
    }
}

我已经测试了这段代码,它在我这边工作。希望它有所帮助。