Jump to content

How can I rewrite this code?


phpscriptcoder

Recommended Posts

Is there anyway to rewrite this code without using a while loop?

 

		foreach ( $BuildArray as $Node => $Item ) {
		if (!$UnFinished) {
			$Element   = $Item[0];
			$Count     = $Item[1];
			$BuildTime = $Item[2];
			while (!$UnFinished ) {

				if ( $Count > 0 ) {
					$CurrentPlanet['b_hangar'] -= $BuildTime;
					$Builded[$Element]++;
					$CurrentPlanet[$resource[$Element]]++;
					$Count--;
					if ($Count == 0) {
						break;
					}
				} else {
					$UnFinished = true;
					break;
				}
			}
		}
		if ( $Count != 0 ) {
			$CurrentPlanet['b_hangar_id'] .= $Element.",".$Count.";";
		}
	}

 

This is in a game script I'm trying to fix up (the code is very bad). The problem is that $Count is often in the millions, and my host has a max_execution_time of 5 seconds.

 

Thanks! I can give more details about the variables if needed.

Link to comment
https://forums.phpfreaks.com/topic/130126-how-can-i-rewrite-this-code/
Share on other sites

<?php
	foreach ( $BuildArray as $Node => $Item ) {
		if (!$UnFinished) {
			$Element   = $Item[0];
			$Count     = $Item[1];
			$BuildTime = $Item[2];
			//while (!$UnFinished ) {

				if ( $Count > 0 ) {
					$CurrentPlanet['b_hangar'] -= $BuildTime * $Count;
					$Builded[$Element] += $Count;
					$CurrentPlanet[$resource[$Element]] += $Count;
					$Count = 0;
					//if ($Count == 0) {
					//	break;
					//}
				//} else {
					$UnFinished = true;
					//break;
				}
			//}

		}
		if ( $Count != 0 ) {
			$CurrentPlanet['b_hangar_id'] .= $Element.",".$Count.";";
		}
	}
?>

<?php
	foreach ( $BuildArray as $Node => $Item ) {
		if (!$UnFinished) {
			$Element   = $Item[0];
			$Count     = $Item[1];
			$BuildTime = $Item[2];
			//while (!$UnFinished ) {

				if ( $Count > 0 ) {
					$CurrentPlanet['b_hangar'] -= $BuildTime * $Count;
					$Builded[$Element] += $Count;
					$CurrentPlanet[$resource[$Element]] += $Count;
					$Count = 0;
					//if ($Count == 0) {
					//	break;
					//}
				//} else {
					$UnFinished = true;
					//break;
				}
			//}

		}
		if ( $Count != 0 ) {
			$CurrentPlanet['b_hangar_id'] .= $Element.",".$Count.";";
		}
	}
?>

 

Thank you for that, works great!

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.