php 根据输入计算值的总和并匹配

jhkqcmku  于 2023-02-11  发布在  PHP
关注(0)|答案(1)|浏览(108)

基于输入计算值的总和并将其与数组中的名称匹配

$input = '500';

    $array1 = array("200" => 'jhon',"300" => 'puppy',"50" => 'liza',
"150" => 'rehana',"400" => 'samra',"100" => 'bolda',);

我需要这样的答案输出

jhon,puppy and bolda,rehana

这段代码创建了一个数组$data,其中包含名称和它们各自的值。然后它使用foreach循环迭代该数组,并从输入中减去每个名称的值,直到输入变为零。从输入中减去的所有值的名称都存储在一个数组$names中。最后,如果数组$names不为空,使用由“”和”“分隔的内聚来回显名称。2如果数组为空,则意味着没有找到匹配,并回显消息“没有找到匹配”。

zy1mlcev

zy1mlcev1#

所以我现在要做一个猜测(这听起来像是在做作业时作弊)。
您需要输出两个名称之和为500的名称对(输入)。
这可能不是最优的解决方案,但它应该是一个有效的解决方案?

$input = 500;

// using shorthand array formatting

$array1 = [
    200 => 'jhon',
    300 => 'puppy',
    50 => 'liza',
    150 => 'rehana',
    400 => 'samra',
    100 => 'bolda'
];

// create an array that holds names we have already processed.
$namesProcessed = [];

// loop over the names trying to find a compatible partner

foreach ($array1 as $points => $name) {
    
    foreach ($array1 as $pointsPotentialPartner => $namePotentialPartner) {

        // Don't partner with yourself...
        if ($name == $namePotentialPartner) {
            continue;
        }

        // Don't partner with someone that has already been processed.
        if (in_array($namePotentialPartner, $namesProcessed)) {
            continue;
        }

        // test if the two partners add up to the input
        if ($input == ($points + $pointsPotentialPartner)) {

           // if this is the first partner set, don't put in 'and'

           if (count($namesProcessed) == 0) {
               echo $name . ', ' . $namePotentialPartner;
           } else {
               echo ' and ' . $name . ', ' . $namePotentialPartner;
           }

           $namesProcessed[] = $name;
           $namesProcessed[] = $namePotentialPartner;
        }
    }
}

希望这个有用。

相关问题