Michdd Posted November 16, 2008 Share Posted November 16, 2008 I'm using some code a certain way, and I know it's very un-efficient, I know making it better would include using like foreach and for statements, but I don't know how to go about doing it. I have a lot of things repeating like this: $monster[1] = "spirit"; $times[1] = "18"; $monster[2] = "golden spirit"; $times[2] = "18"; $monster[3] = "hank"; $times[3] = "15"; Then after the lists of all those it has: for($i = 0; $i < $times[1]; $i++){ $array[] = $monster[1]; } for($i = 0; $i < $times[2]; $i++){ $array[] = $monster[2]; } for($i = 0; $i < $times[3]; $i++){ $array[] = $monster[3]; } that's just an example of the first 3. There's actually more, but how can I make that more efficient? Quote Link to comment Share on other sites More sharing options...
.josh Posted November 16, 2008 Share Posted November 16, 2008 depends on where you're getting the data from. Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted November 16, 2008 Share Posted November 16, 2008 Use a multidimensional array? $monsters = array(); $monsters[0] = array('name'=>'spirit','times'=>18); $monsters[1] = array('name'=>'golden spirit','times'=>18); //etc //sample usage foreach($monsters as $monster){ echo $monster['name']; echo $monster['times']; } Quote Link to comment Share on other sites More sharing options...
Michdd Posted November 16, 2008 Author Share Posted November 16, 2008 I think you're understanding me wrong. I'm not getting the information from anywhere, it's all there, basically I'm using that to put $monster[$i] into the array times[$i], so I can use it later with array_rand, but I know there's got to be a way to compact all that information. Quote Link to comment Share on other sites More sharing options...
.josh Posted November 16, 2008 Share Posted November 16, 2008 Then make use of arrays, as GingerRobot suggested. Better yet, put your data into a database instead of hardcoding it (then put it into an array when needed). Quote Link to comment Share on other sites More sharing options...
Psycho Posted November 16, 2008 Share Posted November 16, 2008 $monster[1] = "spirit"; $times[1] = "18"; $monster[2] = "golden spirit"; $times[2] = "18"; $monster[3] = "hank"; $times[3] = "15"; $array = array(); foreach ($monster as $index => $value) { $array = array_merge($array, array_fill(0, $times[$index], $value)); } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.