2015-11-29 104 views
3

我想写一个圣诞节kris kringle购买清单。 即:史蒂夫购买乔,爱德华购买盟友等。 我有19个人一起工作。检查多维数组中相同数组值的重复项?

目前我已经完成了两个数组。我使用shuffle来混洗原始名称,然后将它们添加到一起以将它们存储到多维数组中。 它的工作..但我有问题。

  1. 洗牌并不关心该人是否购买了自己的礼物。 (即:多维数组具有相同的值,即:[15] =>阵列([0] =>本[1] =>本)

  2. 我将如何去做例外家庭成员,即:?本不能埃伦,戴夫和辣椒买等

我试图寻找不同的排列方式,但我没有更多的答案

我会想isomething。像这样。

如果值相同,则重新洗牌并再次检查。 否则转到下一个值并再次检查。

<?php 

$peoplearray = Array("ben","peter","oscar","jake", "heidi", "Steve", "ed", "matt", "jordan", "gilly" , "Lea", "ellen", "dave", "chilli", "Sean", "Mark", "shane", "ali","dean"); 

shuffle($peoplearray); 
$buying_for = array(); 
$k=0; 

foreach($peoplearray as $value){ 
print "<BR>"; 
$buying_for[$k] = $value; 
$k++; 
} 

$peoplearray = Array("ben","peter","oscar","jake", "heidi", "Steve", "ed", "matt", "jordan", "gilly" , "Lea", "ellen", "dave", "chilli", "Sean", "Mark", "shane", "ali","dean"); 


$total = count($peoplearray); 


$result = array(); 
foreach ($peoplearray as $i => $val) { 
    $result[] = array($val, $buying_for[$i]); 

} 
    for ($row = 1; $row < $total; $row++) { 
    echo "<p><b>Pair $row</b></p>"; 
    echo "<ul>"; 
    for ($col = 0; $col < 2; $col++) { 
    echo " ".$result[$row][$col]." "; 
    } 
    echo "</ul>"; 
} 


?> 
+0

的可能的复制(http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a [如何从在PHP多维数组中删除重复的值] - 多维阵列功能于PHP) –

回答

0

这不会混合的东西了一个相当不错的工作,当谈到与接受者相匹配的买家 - 不完全相信这是你所追求的,但它可能是有用的。

$people = array(
     'ben', 'peter', 'oscar', 'jake', 
     'heidi', 'Steve', 'ed', 'matt', 
     'jordan', 'gilly' , 'Lea', 'ellen', 
     'dave', 'chilli', 'Sean', 'Mark', 
     'shane', 'ali', 'dean', 'bert', 
     'andrew', 'isabelle', 'laura', 'rebecca', 
     'susan', 'huda', 'hazel', 'una', 
     'isla', 'kerry', 'helen', 'thomas' 
    ); 
    $matches=array(); 
    if(count($people) % 2 > 0) exit('There is an odd number of people - somebody would be missed.'); 

    function test($recipient,$buyer){ 
     return $recipient!==$buyer; 
    } 
    function implodearray($array, $newline=false, $sep='=', $delim='&', $tabs=0){ 
     $tmp=array(); 
     if(is_array($array) && !empty($array)){ 
      foreach($array as $key => $value) $tmp[]=$key.$sep.$value; 
      $delimiter = $newline ? $delim . PHP_EOL : $delim; 
      return implode($delimiter . str_repeat(chr(9),$tabs), $tmp); 
     } 
     return false; 
    } 

    foreach($people as $index => $buyer){ 
     $i = rand(0, count($people)-1); 
     while($i==$index) $i = rand(0, count($people)-1); 

     $matches[ ucfirst(strtolower($buyer)) ]=ucfirst(strtolower($people[ $i ])); 
     array_splice(&$people, $i, 1); 
    } 

    echo '<pre>',implodearray($matches, 0,' buys for ', PHP_EOL),'</pre>';