Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to make it so that my multi dimensional array is in a random order. How would you do it?

// This is how the array looks like
print_r($slides);

Array
(
    [0] => Array
        (
            [id] => 7
            [status] => 1
            [sortorder] => 0
            [title] => Pants
        )

    [1] => Array
        (
            [id] => 8
            [status] => 1
            [sortorder] => 0
            [title] => Jewels
        )

    [2] => Array
        (
            [id] => 9
            [status] => 1
            [sortorder] => 0
            [title] => Birdhouse
        )

    [3] => Array
        (
            [id] => 10
            [status] => 1
            [sortorder] => 0
            [title] => Shirt
        )

    [4] => Array
        (
            [id] => 11
            [status] => 1
            [sortorder] => 0
            [title] => Phone
        )

)

// This how the result is if I use array_rand()
print_r(array_rand($slides, 5));

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
)

// This how the result is if I use shuffle()
print_r(shuffle($slides));

1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
547 views
Welcome To Ask or Share your Answers For Others

1 Answer

shuffle() is the way to go here. It prints 1 because shuffle changes the array in-place and returns a boolean, as it is written in the documentation:

Returns TRUE on success or FALSE on failure.

I suggest to also read the documentation of array_rand():

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.


Always read documentation if you use built-in functions. Don't just assume how the work. I bet it took more time to write the question than looking this up.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...