PHP随机化数组哪个键的值是stdClasses

时间:2012-12-15 22:22:42

标签: php arrays

我想将包含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被填充到第三个键

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

1 个答案:

答案 0 :(得分: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')
相关问题