使用php中的不同键删除多维数组中的重复数组

时间:2016-02-01 06:48:19

标签: php arrays multidimensional-array

我的目标是创建多个可能的out 3个数组。

我实现了它,但我遇到了一个问题。

我发现有不同键的重复值。

下面是我试图生成的代码。

$top = array(array('toplinner_name' => M1), array('toplinner_name' => M2));
$flute1 = array(array('f1_name' => M3));
$single_array = compares($top, $flute1); //combaining arrays
$bottom = array(array('bottomlinner_name' => M1), array('bottomlinner_name' => M2));
$single_array = compares($single_array, $bottom); //combaining arrays

function compares($a, $b) {
    if (is_array($a) && is_array($b)) {
        if (count($a) < count($b)) {
            list($a, $b) = array($b, $a);
        }
        $new = array();
        $k = 0;
        for ($i = 0; $i < count($b); $i++) {
            for ($j = 0; $j < count($a); $j++) {
                $new[$k] = array_merge($b[$i], $a[$j]);
                $k++;
            }
        }
        return $new;
    }
    return null;
}

使用上面的代码我将把它作为

Array{
     '0'=>{'toplinner_name'=>'M1','f1_name'=>'M3','bottomlinner_name'=>'M1'},
     '2'=>{'toplinner_name'=>'M1','f1_name'=>'M3','bottomlinner_name'=>'M2'},
     '3'=>{'toplinner_name'=>'M2','f1_name'=>'M3','bottomlinner_name'=>'M1'},
     '4'=>{'toplinner_name'=>'M2','f1_name'=>'M3','bottomlinner_name'=>'M2'},
  }

正如你从上面所看到的那样,2和3是相同的linners所以我需要t0将它们视为一个如何删除那些重复的值..... 我试过下面的代码

$input = array_map("unserialize", array_unique(array_map("serialize", $new)));

但它给了我相同的出局。

我希望的出局应该是

Array{
     '0'=>{'toplinner_name'=>'M1','f1_name'=>'M3','bottomlinner_name'=>'M1'},
     '1'=>{'toplinner_name'=>'M1','f1_name'=>'M3','bottomlinner_name'=>'M2'},
     '2'=>{'toplinner_name'=>'M2','f1_name'=>'M3','bottomlinner_name'=>'M2'},
  }

2 个答案:

答案 0 :(得分:0)

评论中提到的数组示例:

<?

// your array
$res[]=array('toplinner_name'=>'M1','f1_name'=>'M3','bottomlinner_name'=>'M1');
$res[]=array('toplinner_name'=>'M1','f1_name'=>'M3','bottomlinner_name'=>'M2');
$res[]=array('toplinner_name'=>'M1','f1_name'=>'M3','bottomlinner_name'=>'M1');
$res[]=array('toplinner_name'=>'M1','f1_name'=>'M3','bottomlinner_name'=>'M2');

// remove duplicates by using array_map and array_unique for multidimensional array
$duplicateRemoved = array_map("unserialize", array_unique(array_map("serialize", $res)));

// rearrange the array
$rearrangeArray = array_values($duplicateRemoved);

// encode the unique array into json format    
$encodedData = json_encode($rearrangeArray);

// print result    
echo $encodedData;    

?>

答案 1 :(得分:0)

这些行不同,请以粗体显示:

&#39; 0&#39; =&GT; {&#39; T&#39; =&GT;&#39; M的 1 &#39;&#39; F&# 39; =&GT;&#39; M3&#39;&#39; b&#39; =&GT;&#39; M的 1 &#39;},

&#39; 2&#39; =&GT; {&#39; T&#39; =&GT;&#39; M1&#39;&#39; F&#39; =&GT;&#39; M3&#39;&#39; b&#39; = GT;&#39; M的 2 &#39;},

&#39; 3&#39; =&GT; {&#39; T&#39; =&GT;&#39; M的 2 &#39;&#39; F&# 39; =&GT;&#39; M3&#39;&#39; b&#39; =&GT;&#39; M的 1 &#39;},

&#39; 4&#39; =&GT; {&#39; T&#39; =&GT;&#39; M2&#39;&#39; F&#39; =&GT;&#39; M3&#39;&#39; b&#39; = GT;&#39; M的 2 &#39;},