Generate array of random unique numbers in PHP

前端 未结 7 906
再見小時候
再見小時候 2020-12-11 15:09

I\'m trying to generate an array of random numbers from 0-n then shuffle (but ensure that the keys and values DO NOT match).

For example:

0 => 3
1         


        
7条回答
  •  情书的邮戳
    2020-12-11 15:39

    The approach here is to create a range of numbers from 0 to n, and then shuffle. We then look for key value matches, and swap pairs of them. If we don't have a pair to swap, we swap with the last item, unless the item is the last item, then we swap with the first.

    Example shuffle when n is 5:

    array (
      0 => 0,
      1 => 5,
      2 => 1,
      3 => 3,
      4 => 4,
      5 => 2,
    )
    

    Here we have matches for keys:

    0, 3 and 4.
    

    So we swap the values for keys 0 and 3, and 4 with the last.

    array (
      0 => 3,
      1 => 5,
      2 => 1,
      3 => 0,
      4 => 2,
      5 => 4,
    )
    

    (array_key_first could be swapped for 0 given the range here. I've left it as it is more explicit.)

提交回复
热议问题