2010-09-12 3 views
1

Je suis en train d'obtenir des valeurs aléatoires dans un tableau, puis les décomposer plus loin, voici le code initial:tableau PHP exploser

$in = array('foo_1|bar_1', 'foo_2|bar_2','foo_3|bar_3','foo_4|bar_4','foo_5|bar_5'); 
$rand = array_rand($in, 3); 

$in[$rand[0]]; //foo_1|bar_1 
$in[$rand[1]]; //foo_3|bar_3 
$in[$rand[2]]; //foo_5|bar_5 

Ce que je veux est comme ci-dessus, mais avec chaque « foo » et « bar » individuellement accessibles par leur propre clé, quelque chose comme ceci:

$in[$rand[0]][0] //foo_1 
$in[$rand[0]][1] //bar_1 

$in[$rand[1]][0] //foo_3 
$in[$rand[1]][1] //bar_3 

$in[$rand[2]][0] //foo_5 
$in[$rand[2]][1] //bar_5 

J'ai essayé exploser rand $ par une boucle de foreach mais je fais évidemment une erreur n00b:

foreach($rand as $r){ 
$result = explode("|", $r); 
$array = $result; 
} 

Répondre

2

Try this ...

$in = array('foo_1|bar_1', 'foo_2|bar_2','foo_3|bar_3','foo_4|bar_4','foo_5|bar_5'); 

foreach($in as &$r){ 
    $r = explode("|", $r); 
} 

$rand = array_rand($in, 3); 

qui modifie $in "à la volée", il contient la structure de tableau imbriqué que vous cherchez .

maintenant ...

$in[$rand[0]][0] //foo_1 
$in[$rand[0]][1] //bar_1 

$in[$rand[1]][0] //foo_3 
$in[$rand[1]][1] //bar_3 

$in[$rand[2]][0] //foo_5 
$in[$rand[2]][1] //bar_5 

Je pense que c'est ce que vous cherchez.

+0

A travaillé parfaitement, merci! –

4

Vous étiez proche:

$array = array(); 
foreach ($in as $r) 
    $array[] = explode("|", $r); 
1
foreach($rand as $r){ 
    $result = explode("|", $r); 
    array_push($array, $result); 
} 
Questions connexes