H
H
hello_world_6662021-06-17 18:21:27
PHP
hello_world_666, 2021-06-17 18:21:27

How to shuffle a multidimensional array?

Hello, how to shuffle a given array:

Array(
    [0]=>Array(
             [title]       => 'Title 1'
             [description] => 'description here'
         )
    [1]=>Array(
             [title]       => 'Title 2'
             [description] => 'description here'           
         )
    [2]=>Array(
             [title]       => 'Title 3'
             [description] => 'description here'           
         )
)


To get the output:

Array(
    [0]=>Array(
             [title]       => 'Title 2'
             [description] => 'description here'
         )
    [1]=>Array(
             [title]       => 'Title 3'
             [description] => 'description here'           
         )
    [2]=>Array(
             [title]       => 'Title 1'
             [description] => 'description here'           
         )
)


Thanks for the help)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BornTo FreeFall, 2021-06-17
@hello_world_666

I'm not sure what the question is, but I'll try to suggest the following:

function shuffle_assoc($list) {
    if (!is_array($list)) return $list;
    $keys = array_keys($list);
    shuffle($keys);
    $random = [];
    foreach ($keys as $key)
        $random[$key] = $list[$key];

  return $random;
}

Result: Link - screenshot, console output - Link

S
Stalker_RED, 2021-06-17
@Stalker_RED

shuffle($arr);
https://www.php.net/manual/en/function.shuffle.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question