Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multi dimensional array in random order

Tags:

php

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
like image 439
Cudos Avatar asked Jun 15 '11 08:06

Cudos


People also ask

Can you sort a multidimensional array?

You can sort by any key (also nested like 'key1. key2. key3' or ['k1', 'k2', 'k3'] ) It works both on associative and not associative arrays ( $assoc flag)

What is multi-dimensional array with example?

A multi-dimensional array is an array with more than one level or dimension. For example, a 2D array, or two-dimensional array, is an array of arrays, meaning it is a matrix of rows and columns (think of a table). A 3D array adds another dimension, turning it into an array of arrays of arrays.

What is 1D/2D and multidimensional array?

A 1D array is a simple data structure that stores a collection of similar type data in a contiguous block of memory while the 2D array is a type of array that stores multiple data elements of the same type in matrix or table like format with a number of rows and columns.


1 Answers

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.

like image 108
Felix Kling Avatar answered Sep 30 '22 20:09

Felix Kling