...

View Full Version : multidimensional_array_rand() - same as array_rand but for multidimensional arrays



BornKillaz
07-27-2012, 02:55 PM
Hi! :)

Ok, so the other day I need to randomize an array. Usually I use PHP's array_rand to archive this, however I need it for a multidimensional array, and array_rand can only deal with simple arrays returning it's keys. I needed keys and values in a multidimensional array!

I toke a look at the PHP's website, for comments in the array_rand() function (http://php.net/manual/en/function.array-rand.php#allnotes), as usually people leave snippets for most of the things you need related to a specific function.

Well, I did find a few possible solutions in there on how to do this with multidimensional arrays, but the snippets were just insane!! They were full of code with a terrible performance impact, so I just could not make use of any of those, I even haven't test them, no way, I just move on.

So, I like clean code, and with just the enough lines. Things are simple and people use to complicate them, and the combined side effects on CPU memory usage and performance are huge.

OK, it was time for me to create a function that would do what I want, and in my way. And I did. I admit it toke me about 3 hours to come with the final result, and I just want to share it with you.

In fact, we'll need two functions, because one of them will act as a callback command.

Here we go:



<?php

/**
* multidimensional_array_rand()
*
* @param array $array
* @param integer $limit
* @return array
*/
function multidimensional_array_rand( $array, $limit = 2 ) {

uksort( $array, 'callback_rand' );

return array_slice( $array, 0, $limit, true );
}

/**
* callback_rand()
*
* @return bool
*/
function callback_rand() {

return rand() > rand();

}
?>


That's it, now try it out!


<?php

// A multidimensional array
$my_array = array( 153 => 'ABC',
403 => array( 'DEF' => 'Other Data' ),
306 => 'GHI',
172 => 'JKL',
838 => 'MNO',
197 => 'PQRS' );

// Let's rand it and limit it to 3 results
print_r( multidimensional_array_rand( $my_array, 3 ) );


// Possible output would be
// Array ( [172] => JKL [197] => PQRS [403] => Array ( [DEF] => Other Data ) )
?>



That's it. Let me know if it was useful for you. :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum