检查多维数组中相同数组值的重复项?

时间:2015-11-29 09:50:23

标签: php arrays multidimensional-array

我正在尝试写一张圣诞节kris kringle购买清单。 即:史蒂夫为乔买,爱德华为盟友购买等。 我有19个人在一起工作。

目前我已经完成了两个阵列。我使用shuffle来移动原始名称,然后将它们一起添加到一个多维数组中。 它有效..但我有问题。

  1. 如果这个人购买自己的礼物,洗牌并不在乎。 (即:多维数组具有相同的值。即:[15] =>数组([0] => Ben [1] => Ben)

  2. 我如何为家庭成员制作例外,即:本不能为Ellen,dave和辣椒购买?等等。

  3. 我尝试过查看各种数组方法,但我没有更多答案。

    我会想到这样的事情。

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

    <?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>";
    }
    
    
    ?>
    

1 个答案:

答案 0 :(得分: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>';