Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

php - multi dimensional array in random order

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...