2

how to shuffle arrays in array ? I tried lots of way but I can't achieve that. I think it's very simple but I'm stuck on that.

Array
(
    [2] => Array
        (
            [0] => 12011190
            [1] => 12011158
            [2] => 12011583
            [3] => 12012107
            [4] => 12011222
            [5] => 12010638
            [6] => 12013836
            [7] => 12012232
            [8] => 12011256
            [9] => 12010007
            [10] => 12012531
            [11] => 12012182
            [12] => 12013253
        )

    [6] => Array
        (
            [0] => 12011565
            [1] => 12010020
            [2] => 12011352
            [3] => 12014366
            [4] => 12011879
            [5] => 12011449
        )
)

I want to shuffle within arrays. I hope explain...

1
  • which value you want to shuffle and where? Commented Jan 18, 2013 at 14:15

2 Answers 2

9

As far as I know, you can do it like this (assuming you want to shuffle every sub-array independently):

foreach($array AS &$element) {
    shuffle($element);
}

Or maybe like this:

array_walk($array, function(&$value, $key) {
    shuffle($value);
});
Sign up to request clarification or add additional context in comments.

1 Comment

array_walk is suitable for me. Thanks for the response, But Vlad Preda's answer is better for my code. (Next answer)
0

Here is a recursive multi-level function you can use.

function shuffle_array($arr) {
    if (!is_array($arr)) return $arr;
    shuffle($arr);
    foreach ($arr as $key => $a) {
        if (is_array($a)) {
            $arr[$key] = shuffle_array($a);
        }
    }

    return $arr;
}

print_r(shuffle_array($array));

1 Comment

Thanks a lot. This one is my solution. You saved my day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.