Reputation: 102
I have tried this now about 20 different ways, set it down and picked it back up several times and I am at a loss for what I am doing wrong. I am trying to create an array of arrays from three separate arrays. The first array I iterate through is a list of dates. Then I iterate through a list of cabins (this is a simple camp scheduling program), and then I randomly assign an activity to each of the cabins from a third array.
The three arrays are $cabins
, $activities
, and $checkeddates
//swaps key-value so cabin names are keys
$cabins = array_flip( $cabins );
//sets each key value pair to be cabinname=> null
erase_val( $cabins );
foreach ( $checkeddates as $dates ) {
$uberarray[] = $dates;
}
$uberarray = array_flip( $uberarray );
foreach ( $uberarray as $k => $v ) {
$uberarray[$k] = $cabins;
}
At this point, a var_dump shows that I have an array of dates each containing an array of cabins names with null values, from this point I have tried a dozen things and this is just where I left it, trying a process of elimination to figure out what it isn't.
foreach ( $uberarray as $k => $v ) {
shuffle( $activities );
$s = $activities[0];
$uberarray[] = $s;
}
In the end, I was thinking to build the large array (with some additional rules not yet written in to prevent multiple assignments of the same thing and such. And then as one function I would iterate through the established combinations in the array to write it to the database.
Edit: Request for how I want it to look in the end:
array
'ThuJan1st' =>
array
'cabin 1' => randomactivity1
'cabin 2' => randomactivity2
'cabin 3' => randomactivity3
Currently I have 2 out of 3, but I can not seem to randomly add the activities as values.
Edit: This is what @kunal 's suggestion produced:
array
'ThuJan1st' =>
array
'cabin 1' => randomactivity1
'cabin 2' => randomactivity2
'cabin 3' => randomactivity3
array
'FriJan2nd' =>
array
'cabin 1' => randomactivity4
'cabin 2' => Null
'cabin 3' => Null
Once it iterated through activities a single time, nothing else was assigned a value.
Upvotes: 0
Views: 489
Reputation: 1389
foreach ($checkeddates as $date) {
shuffle( $activities );
foreach ($cabins as $cabin) {
foreach ($activities as $activity) {
$uberarray[$date][$cabin] = $activity;
}
}
}
EDIT: The above answer is incorrect. It assigns the same activity to each date/cabin pair. The below answer should give you what you are looking for.
$checkeddates = array('ThuJan1st');
$cabins = array('cabin 1','cabin 2','cabin 3');
foreach ($checkeddates as $date) {
$activities = array('randomactvitiy1','randomactivity2','randomactivity3');
shuffle( $activities );
foreach ($cabins as $cabin) {
$uberarray[$date][$cabin] = array_pop($activities);
}
}
var_dump($uberarray);
Upvotes: 2