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 は 3 番目のキーにシャッフルされます

そして、これを正しい方法でランダム化する方法がわかりません。

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 に答える