2个不同的数组具有不同的值

时间:2016-11-30 09:30:58

标签: php arrays

我的问题可能听起来很傻,但我知道这是可能的。我实际上是想让mysql中的数组与我已经拥有的shuffle数组不同。我想维护数组键,只是维持不同顺序的值。

以下是示例

来自MYSQL的数组:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
)

shuffle之后的数组:

Array
(
    [0] => 3
    [1] => 7
    [2] => 8
    [3] => 4
    [4] => 1
    [5] => 2
    [6] => 5
    [7] => 6
)

如果您注意到,MYSQL array键3的值与shuffle array相同,我希望它与众不同。我怎么能这样做?

这是我的代码:

function get_random_elements($array) {
    $ori_array = $array;

    echo "<pre>";
    print_r($ori_array);
    echo "</pre>";

    shuffle($array);

    echo "<pre>";
    print_r($array);
    echo "</pre>";

    for($x=0; $x<count($array); $x++) {
        if ($array[$x] == $ori_array[$x])
        {
            $dupliarray[] = "Array value: ".$array[$x]." Key :".$x;
            unset($array[$x]);
        }

    }

    echo "<pre>";
    print_r($dupliarray);
    echo "</pre>";

}

$mysql_array = array(0=>'1',1=>'2',2=>'3',3=>'4',4=>'5',5=>'6',6=>'7',7=>'8');

get_random_elements($mysql_array);

2 个答案:

答案 0 :(得分:2)

一种解决方案可以是对数组进行混洗,直到它与源数组完全不同为止:

$sourceArray = [0, 1, 2, 3, 4, 5, 6, 7, 8];
$shuffledArray = $sourceArray; //because function shuffle will change passed array

shuffle($shuffledArray);    
while (count(array_intersect_assoc($sourceArray, $shuffledArray))) {
    shuffle($shuffledArray);
}

echo '<pre>';
var_dump($sourceArray, $shuffledArray);

答案 1 :(得分:0)

我建议使用此变体:Code in sandbox

$startArray = [
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 4,
    4 => 5,
    5 => 6,
    6 => 7,
    ];

function getShuffledArray($startArray) {

    $shuffledArray = [];

    // save value of last element for situation when we have last 2 elements of start array and one of them - last
    $lastElement = end($startArray);

    while (count($startArray)) {
        $candidateIndex = array_rand($startArray);
        if ($candidateIndex == count($shuffledArray)) {
            while ($candidateIndex == count($shuffledArray)) {
                $candidateIndex = array_rand($startArray);
            }
        }
        $shuffledArray[] = $startArray[$candidateIndex];
        unset($startArray[$candidateIndex]);

        // shuffle last two elements when one of them last (in start array)
        if (count($startArray) == 2 && end($startArray) == $lastElement) {
            $shuffledArray[] = end($startArray);
            $shuffledArray[] = reset($startArray);
            $startArray = [];
        }
    }

    return $shuffledArray;
}

$shuffledArray = getShuffledArray($startArray);
print_r ($shuffledArray);