PHP随机化数组中的哪个键';s值是stdClasses

PHP随机化数组中的哪个键';s值是stdClasses,php,arrays,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

我想随机化一个数组,其中包含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*/)
)
我试过这个函数,但是这个函数也会使stdclass失效,这不好。 例如,zero键的class->id是shuffeld到第三个键


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

这将洗牌您的数组并保持键/值关联

$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')

因此,您正在尝试对其进行无序化,除了希望值保持不变和数字键被无序化之外?是的,实际上我希望实现与MySQL的ORDER BY RAND()相同的效果。这些对象是由数字键还是字符串键索引的?您确定数字键/值关联实际上很重要吗?字符串如示例中所示,ID、名称等。是的,这样做很重要。首先,我没有意识到原始数组来自的代码中有一个错误,这导致了洗牌中的问题。谢谢你的帮助。