0

我想随机化一个数组,其中包含 stdClasses 作为每个键的值,并且 stdclasses 顺序必须是原始的。

例如原始数组如下所示:

Array(
 [0]=>stdClass(/*lots of keys with value that must stay here and stay in order 
                 for example [id]=1 [name]=One*/)
 [1]=>stdClass(/*lots of keys with value that must stay here and stay in order 
                 for example [id]=2 [name]=Two*/)
 [2]=>stdClass(/*lots of keys with value that must stay here and stay in order 
                 for example [id]=3 [name]=Three*/)
 [3]=>stdClass(/*lots of keys with value that must stay here and stay in order 
                 for example [id]=4 [name]=Four*/)
)

这就是我想要实现的目标:

Array(
 [3]=>stdClass(/*lots of keys with value that must stay here and stay in order 
                 for example [id]=4 [name]=Four*/)
 [0]=>stdClass(/*lots of keys with value that must stay here and stay in order 
                 for example [id]=1 [name]=One*/)
 [1]=>stdClass(/*lots of keys with value that must stay here and stay in order 
                 for example [id]=2 [name]=Two*/)
 [2]=>stdClass(/*lots of keys with value that must stay here and stay in order 
                 for example [id]=3 [name]=Three*/)
)

我尝试了这个函数PHP Random Shuffle Array Maintaining Key => Value但这也对 stdClasses 进行了洗牌,这并不好。例如零键的 class->id 被改组到第三键

而且我不知道如何以正确的方式随机化它。

4

1 回答 1

0

这将打乱您的数组并保持键/值关联。

$array = array('a'=> '1', 'b'=>'2', 'c'=>'3');

function shuffle_assoc($array) {
    $keys = array_keys($array);
    shuffle($keys);

    $result = array();
    foreach ($keys as $k) {
        $result[$k] = $array[$k];
    }

    return $result;
}

$result = shuffle_assoc($array);

// $result = array('b'=>'2', 'c'=>'3', 'a'=>'1')
于 2012-12-15T23:07:05.357 回答