2

我有 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] 这样的唯一键?

4

2 回答 2

3

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

于 2013-05-12T15:27:00.507 回答
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;
    }
}

我已经测试了这段代码,它适用于我。希望能帮助到你。

于 2014-07-03T03:46:20.137 回答