2015-11-29 100 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>';