php, how to jumble / randomize order of associative array while keeping key/value pairs

前端 未结 2 532
不知归路
不知归路 2021-01-21 02:24

what is the php function to randomize the associative array while keeping key/values pairs. I don\'t mean to just randomly pick out a key value pair, but actually changing the

相关标签:
2条回答
  • 2021-01-21 02:48

    You could use shuffle() on array_keys, then loop around your array adding them to the list in the new order.

    E.g.

    $shuffleKeys = array_keys($array);
    shuffle($shuffleKeys);
    $newArray = array();
    foreach($shuffleKeys as $key) {
        $newArray[$key] = $array[$key];
    }
    
    0 讨论(0)
  • 2021-01-21 03:00

    A comment on shuffle() might do the trick: http://ch2.php.net/manual/en/function.shuffle.php#104430

    <?php
    function shuffle_assoc( $array )
    {
       $keys = array_keys( $array );
       shuffle( $keys );
       return array_merge( array_flip( $keys ) , $array );
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题