【问题标题】:Randomize some elements inside an array随机化数组中的一些元素
【发布时间】:2015-11-16 23:30:39
【问题描述】:

您好,我有一个集合或数组:

$arr = ['1','2','3','4','5','6','7','8','9','0'];
shuffle($arr);

这将返回数组的随机顺序。但是如果'3','4''8','9','0' 必须在一起,我该如何编码?我的意思是其他值可以随机排列,但这些 '3','4''8','9','0' 必须连接在一起。

【问题讨论】:

    标签: php arrays random


    【解决方案1】:

    另一种方法是先获取这些有序元素(另一个副本),然后将原始元素打乱,然后使用 union 再次合并它们:

    $arr = ['1','2','3','4','5','6','7','8','9','0'];
    $arr2 = array_filter($arr, function($e){ // get those elements you want preversed
        return in_array($e, [3, 4, 8, 9, 0]);
    });
    shuffle($arr); // shuffle the original
    $ordered = $arr2 + $arr; // use union instead of array merge
    ksort($ordered); // sort it by key
    
    print_r($ordered);
    

    Sample Output

    【讨论】:

    • ngayun ko lng na 通知,Hokage Du30 ikaw ba yan?
    【解决方案2】:

    许多可能的解决方案,一个例子

    <?php
    $arr = ['1','2',['3','4'],'5','6','7',['8','9','0']];
    shuffle($arr);
    // and then flatten the array  ..somehow, e.g.
    array_walk_recursive($arr, function($e) { echo $e, ' '; });
    

    【讨论】:

      猜你喜欢
      • 2010-10-23
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2013-11-14
      • 2019-01-31
      • 1970-01-01
      • 2019-02-21
      相关资源
      最近更新 更多