Wednesday, August 24, 2011

[PHP] Sorting associative array by random order

Assumed that we have an associative array like this:
$books = array();
$books[0] = array();
$books[0]["name"] = "Book1";
$books[0]["author"] = "John";

$books[1] = array();
$books[1]["name"] = "Book2";
$books[1]["author"] = "Sam";

$books[2] = array();
$books[2]["name"] = "Book3";
$books[2]["author"] = "James";

Now, we are going to shuffle this associative array. First of all, we have to create a new array to store the lucky number for each "book", this lucky number will be act as a key.
$luckydraw = range(0, count($books));
shuffle($luckydraw);

OK, we now redraw the array and assign the lucky number to each book.
$list = array();

$c = 0;
foreach ($books as $key => $value) {
   $list[$key] = $value;
   $luck[$key] = $luckydraw[$c];
   $c++;
}

 And finally, sorting it by the lucky number.

array_multisort($luck, SORT_ASC, $list);
Related Posts Plugin for WordPress, Blogger...