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

3
我正在尝试编写一个圣诞节礼物清单。例如:Steve为Jo购买,Edward为Ally购买等。我需要处理19个人。
目前我已经完成了两个数组。我使用shuffle来打乱原始名称,然后将它们相加并存储到多维数组中。它可以工作,但是有以下问题:
1. shuffle不会考虑到一个人买自己的礼物。(即:多维数组具有相同的值。例如:[15]=>Array([0]=>Ben[1]=>Ben)) 2. 如何为家庭成员制定例外规则?例如:Ben不能为Ellen、Dave和Chilli购买礼物等。
我已经尝试查看各种数组方法,但是没有更多答案。
我想到了这样的思路:
如果值相同,请重新洗牌并再次检查。 否则,继续下一个值并再次检查。
<?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>";
}


?>

可能是如何在PHP中从多维数组中删除重复值的重复内容。 - i am me
1个回答

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>';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接