Assotsiatiivne jada – juhuslik sorteerimine – php

  |   by kadriad   |   Blogi, php  |  No Comments

Oli vaja assotstiatiivset jada sorteerida juhuslikult ning hiljem oli vaja nii key kui value kätte saada.

Ülesanne tundub küll lihtne, lõpuks panin kokku õiged skriptid.

Abi sain:

http://stackoverflow.com/questions/4102777/php-random-shuffle-array-maintaining-key-value

Minu kood siis:

$prices = array( 'one'=>G );
$prices['two'] = O;
$prices['three'] = D;
$prices['four'] = J;
$prices['five'] = U;
$prices['six'] = L;
 
 
function shuffle_with_keys(&$array) {
/* Auxiliary array to hold the new order */
$aux = array();
/* We work with an array of the keys */
$keys = array_keys($array);
/* We shuffle the keys */
shuffle($keys);
/* We iterate thru' the new order of the keys */
foreach($keys as $key) {
/* We insert the key, value pair in its new order */
$aux[$key] = $array[$key];
/* We remove the element from the old array to save memory */
unset($array[$key]);
}
/* The auxiliary array with the new order overwrites the old variable */
$array = $aux;
}
shuffle_with_keys($prices);
 
 
while ( list( $product, $price ) = each( $prices ) ){
?>
<td class="dark"><div id="<?php echo $product ?>" class="drag <?php echo $product ?>"><?php echo $price ?></div></td>
<?php
}//end for
?>