2010-11-05 17 views
33

Ho cercato su google la risposta, ma non riesco a trovare qualcosa di infallibile e non posso davvero permettermi di rovinare tutto (andando in diretta in un sito di produzione).PHP Shuffle Array casuale Mantenere la chiave => Valore

Quello che ho è una ricerca avanzata con oltre 20 filtri, che restituisce un array che include un ID e una Distanza. Quello che devo fare è mescolare questi risultati per visualizzarli in un ordine casuale ogni volta. La matrice ho che esce al momento è:

Array (
    [0] => Array ([id] => 1 [distance] => 1.95124994507577) 
    [1] => Array ([id] => 13 [distance] => 4.75358968511882) 
    [2] => Array ([id] => 7 [distance] => 33.2223233233323) 
    [3] => Array ([id] => 21 [distance] => 18.2155453552336) 
    [4] => Array ([id] => 102 [distance] = 221.2212587899658) 
) 

Cosa devo potere fare è randomizzare o l'ordine di questi ogni volta ma mantenere l'ID e la distanza coppie, vale a dire:

Array (
    [4] => Array ([id] => 102 [distance] = 221.2212587899658) 
    [1] => Array ([id] => 13 [distance] => 4.75358968511882) 
    [3] => Array ([id] => 21 [distance] => 18.2155453552336) 
    [2] => Array ([id] => 7 [distance] => 33.2223233233323) 
    [0] => Array ([id] => 1 [distance] => 1.95124994507577) 
) 

Grazie :)

risposta

68

il first user post sotto la documentazione shuffle:

Shuffle come sociative e array non associativo preservando la chiave , coppie di valori. Restituisce anche l'array shoppled anziché shuffling sul posto. caso

function shuffle_assoc($list) { 
    if (!is_array($list)) return $list; 

    $keys = array_keys($list); 
    shuffle($keys); 
    $random = array(); 
    foreach ($keys as $key) { 
    $random[$key] = $list[$key]; 
    } 
    return $random; 
} 

prova:

$arr = array(); 
$arr[] = array('id' => 5, 'foo' => 'hello'); 
$arr[] = array('id' => 7, 'foo' => 'byebye'); 
$arr[] = array('id' => 9, 'foo' => 'foo'); 
print_r(shuffle_assoc($arr)); 
print_r(shuffle_assoc($arr)); 
print_r(shuffle_assoc($arr)); 
+0

ho provato, ma la matrice sembra uscire nello stesso ogni ordine utilizzando print_r ($ arr) – lethalMango

+0

@lethalMango - orso con me, sto cercando dentro. – karim79

+0

Ok, grazie :) – lethalMango

12

Come di 5.3.0 si poteva fare:

uksort($array, function() { return rand() > rand(); }); 
+0

questo potrebbe non produrre un array uniformemente mischiato a seconda dell'ordinamento Algoritmo coinvolto – marcusklaas

+0

Mescolare gli array con l'ordinamento su rand() è molto lento e fornisce una riproduzione casuale. – Rich

+1

può essere leggermente migliorato 'uksort ($ array, function() {return rand()> getrandmax()/2});' –

1

Prova a usare l'algoritmo di Fisher-Yates Da here:

function shuffle_me($shuffle_me) { 
    $randomized_keys = array_rand($shuffle_me, count($shuffle_me)); 
    foreach($randomized_keys as $current_key) { 
     $shuffled_me[$current_key] = $shuffle_me[$current_key]; 
    } 
    return $shuffled_me; 
} 

Ho dovuto implementare qualcosa di simile a questo per la mia tesi di laurea triennale, e funziona molto bene.

+2

Ciao Jesse, ho esattamente lo stesso codice di script alla mia pagina: funzione shuffle_me ($ shuffle_me) {$ randomized_keys = array_rand ($ shuffle_me, count ($ shuffle_me)); foreach ($ randomized_keys as $ current_key) { $ shuffled_me [$ current_key] = $ shuffle_me [$ current_key]; } return $ shuffled_me; } Funziona perfettamente con PHP4, tuttavia non funziona con PHP5. Penso che il motivo sia la modifica nel registro array_rand: 5.2.10 - L'array di chiavi risultante non viene più mescolato. Cosa dovrei cambiare per funzionare su un server PHP5? Grazie –

4

Date un'occhiata a questa funzione qui:

 $foo = array('A','B','C'); 


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 */`enter code here` 
    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($foo); 
     var_dump($foo); 

post originale qui: http://us3.php.net/manual/en/function.shuffle.php#83007

3

ho avuto un momento difficile con la maggior parte delle risposte fornite - così ho creato questo piccolo frammento che ha avuto le mie matrici e randomizzati, pur mantenendo le loro chiavi:

function assoc_array_shuffle($array) 
{ 
    $orig = array_flip($array); 
    shuffle($array); 
    foreach($array AS $key=>$n) 
    { 
     $data[$n] = $orig[$n]; 
    } 
    return array_flip($data); 
} 
+0

Funziona solo con valori di stringa e interi non uguali (confronto casuale). – hakre

2
function shuffle_assoc($array) 
{ 
    $keys = array_keys($array); 
    shuffle($keys); 
    return array_merge(array_flip($keys), $array); 
} 
+1

Questo non sembra fornire risultati corretti per gli array con chiavi di tipo intero. – Andy

2

Charles Iliya Krempeaux ha un nice writeup sulla questione e una funzione che ha funzionato molto bene per me:

function shuffle_assoc($array) 
{ 
    // Initialize 
     $shuffled_array = array(); 


    // Get array's keys and shuffle them. 
     $shuffled_keys = array_keys($array); 
     shuffle($shuffled_keys); 


    // Create same array, but in shuffled order. 
     foreach ($shuffled_keys AS $shuffled_key) { 

      $shuffled_array[ $shuffled_key ] = $array[ $shuffled_key ]; 

     } // foreach 


    // Return 
     return $shuffled_array; 
} 
0

ho provato la soluzione più votazione non ha fatto la lista casuale popolare. Questa è la modifica che ho fatto per farlo funzionare. Voglio che la mia chiave dell'array a partire dal 1.

$list = array_combine(range(1,10),range(100,110)); 
$shuffle_list = shuffle_assoc($list); 


function shuffle_assoc($list) 
{ 
    if (!is_array($list)) return $list; 

    $keys = array_keys($list); 
    shuffle($list); 
    $random = array(); 
    foreach ($keys as $k => $key) { 
     $random[$key] = $list[$k]; 
    } 
    return $random; 
} 
Problemi correlati