如何使用php在数组中创建唯一的值对

时间:2016-11-12 09:14:21

标签: php arrays

我想在array中显示唯一的对值,并且只有当该对的加法是偶数时才打印该对。要使用的语言是PHP。

1 个答案:

答案 0 :(得分:0)

由于你没有在你的问题中解释清楚,但我尝试过,也许有帮助。

<?php
$range1 = range(1,2000);//change as per your requirement

$i = 5; //change as per your requirement

$UniqueEvenPairs = array();
while($i > 0){

    shuffle($range1);
    $addition = (($range1[0] + $range1[10]));
    if($addition % 2 == 0){
        $UniqueEvenPairs[$i] = array("val_1"=>$range1[0] , "val_2"=>$range1[10] , "addition" =>$addition);
        $i--;
    }
}

echo "<pre>";print_r($UniqueEvenPairs);

?>

<强> 输出

Array
(
    [5] => Array
        (
            [val_1] => 836
            [val_2] => 500
            [addition] => 1336
        )

    [4] => Array
        (
            [val_1] => 293
            [val_2] => 319
            [addition] => 612
        )

    [3] => Array
        (
            [val_1] => 1604
            [val_2] => 742
            [addition] => 2346
        )

    [2] => Array
        (
            [val_1] => 432
            [val_2] => 1606
            [addition] => 2038
        )

    [1] => Array
        (
            [val_1] => 896
            [val_2] => 1766
            [addition] => 2662
        )

)