Reputation: 75
Basically my problem is that i cannot shuffle an array that is inside another array. To be more specific i want to shuffle the array that is the value of 'Variante de raspuns:':
$intrebari=array(
array('Enunt:'=>'2+2=','Variante de raspuns:'=>array(2,5,6,4),'Raspuns corect:'=>4,'Punctaj obtinut:'=>'25p'),
array('Enunt:'=>'2*2=','Variante de raspuns:'=>array(3,4,8,1),'Raspuns corect:'=>4,'Punctaj obtinut:'=>'25p'),
array('Enunt:'=>'2/2=','Variante de raspuns:'=>array(1,3,4,8),'Raspuns corect:'=>1,'Punctaj obtinut:'=>'25p'),
array('Enunt:'=>'2-2=','Variante de raspuns:'=>array(2,3,0,4),'Raspuns corect:'=>0,'Punctaj obtinut:'=>'25p')
);
The function i thought of is:
function amestecVariante(&$array){
foreach($array as $intrebare){
foreach($intrebare as $k=>$v)
if($k=='Variante de raspuns:')
shuffle($v);}
}
For now i only want to display the array with the shuffled 'Variante de raspuns:'. I have another function to display it so it goes something like this in the end:
amestecVariante($intrebari);
afisare($intrebari);
The problem is that the 'Variante de raspuns' array is not shuffled and it's displayed as it is initially. Also i really want to understand why my function doesn't work, i'm not looking for another solution unless mine is no good at all. Thank you in advance.
Upvotes: 0
Views: 117
Reputation: 106385
Do this instead:
function amestecVariante(&$array){
foreach($array as &$intrebare){
shuffle($intrebare['Variante de raspuns:']);
}
}
Demo.
You don't have to iterate over the inner arrays - you just access the array to be shuffled directly (by key). But you do need to make PHP understand that you will modify this array within foreach
- that's what reference in &$intrebare
is for.
Upvotes: 3