Jump to content

[SOLVED] How can I make this more efficient?


Michdd

Recommended Posts

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?

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'];
}

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.

$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));
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.