Jump to content

Foreach Loop Problem


Ardivaba

Recommended Posts

Hi, i am new in this forum, and this is my first post. I need help, and fast, and i would be very, very, very thankfull if someone could help me or guide me towards solution.

 

I've been trying to solve this puzzle 3 hours and im...well...desperate.

 

squad.jpg

This is the screenshot of the page squads.php page. In there you can create squads, and squads must have == 5 units in them, not less, not more in order to have $error = 0.

 

Previous script was to be executed in case there is no error. Now what i wanted to do was that, if i have 3 Special Forces units, and 2 Sniper units, then loop completes mysql insert statment:

 

"INSERT INTO squads (id, squad_unit1,squad_unit2,squad_unit3, squad_unit4, squad_unit5, user) VALUES('', '$unit1', '$unit2', '$unit3', '$unit4', '$unit5', '$user')"

So if i would have 3 Special Forces units, and 2 Sniper units to create an squad, then the query would look like:

"INSERT INTO squads (id, squad_unit1,squad_unit2,squad_unit3, squad_unit4, squad_unit5, user) VALUES('', 'unit_specforces', 'unit_specforces', 'unit_specforces', 'unit_sniper', '$unit_sniper', 'YoungStudent')"

 

I am very unfamiliar with foreach loop type, as i googeled it, but still didnt catch it's true concept...so i am unable to complete this loop in order, that it would check more than 1 unit classes until 5 unit spaces are filled.

 

if($error != 1){
   $units = array();
   foreach(range(1,$create_squad_unit_specforce_sum) as $i) {
	  $units[$i] = "Special Force";
	  echo "Unit $i:" . $units[$i];
   }
}

 

I cant figure out that how can i improve the loop so, that it will check more than one unit type (unit_specforce) if $create_squad_unit_specforce_sum isn't enough (5).

 

Thank you for your help.

 

Also, full code of the page squads.php, i know i have numerous security risks in there, i was going to take care of them later, when i've finished the basics...but if anyone has good tips to share with me, feel free to share them with me.

 

<?php
require_once('auth.php');
require_once('functions.php');
require_once('costs.php');

//Hehehe
$login = Ardivaba;

$result = mysql_query("SELECT * FROM squads WHERE user='$login'")
or die(mysql_error());  
$player = mysql_fetch_array( $result );
?>

<?php include("header.php"); ?>

<?php
$error = 0;

if($_GET["action"] == create_squad){
$create_squad_unit_specforce_sum = $_POST["create_squad_unit_specforce"];
$create_squad_unit_sniper_sum = $_POST["create_squad_unit_sniper"];
$create_squad_unit_assault_sum = $_POST["create_squad_unit_assault"];
$create_squad_unit_support_sum = $_POST["create_squad_unit_support"];
$create_squad_unit_engineer_sum = $_POST["create_squad_unit_engineer"];
$create_squad_unit_medic_sum = $_POST["create_squad_unit_medic"];
$create_squad_unit_antitank_sum = $_POST["create_squad_unit_antitank"];

$create_squad_units = 	$create_squad_unit_specforce_sum	+ 
						$create_squad_unit_sniper_sum		+ 
						$create_squad_unit_assault_sum		+ 
						$create_squad_unit_support_sum		+ 
						$create_squad_unit_engineer_sum		+ 
						$create_squad_unit_medic_sum		+
						$create_squad_unit_antitank_sum; 

if($create_squad_units > 5){
	$teade = "You can't have that many units in squad!";
	$error = 1;
}

if($create_squad_unit_specforce_sum > $player['unit_specforce']){
	$teade = "You dont have that many Special Force units!";
	$error = 1;
}

if($create_squad_unit_sniper_sum > $player['unit_sniper']){
	$teade = "You dont have that many Sniper units!";
	$error = 1;
}

if($create_squad_unit_assault_sum > $player['unit_assault']){
	$teade = "You dont have that many Assault units!";
	$error = 1;
}

if($create_squad_unit_support_sum > $player['unit_support']){
	$teade = "You dont have that many Support units!";
	$error = 1;
}

if($create_squad_unit_engineer_sum > $player['unit_engineer']){
	$teade = "You dont have that many Engineer units!";
	$error = 1;
}

if($create_squad_unit_medic_sum > $player['unit_medic']){
	$teade = "You dont have that many Medic units!";
	$error = 1;
}

if($create_squad_unit_antitank_sum > $player['unit_antitank']){
	$teade = "You dont have that many Anti-Tank Force units!";
	$error = 1;
}

if($error != 1){
   $units = array();
   foreach(range(1,$create_squad_unit_specforce_sum) as $i) {
	  $units[$i] = "Special Force";
	  echo "Unit $i:" . $units[$i];
   }
}
}
?>

<?php include("side.php"); ?>

<div id="main">
<p class="user-links"><a href="#">Register now</a> - <a href="#">Forgot password</a></p>
<p class="time">Money: <span><?php echo $player['money']; ?></span></p>
<div id="content">
	<h2 class="cat"><a name="help_text" href="#help_text"><?php if(isset($teade)) { echo $teade; } else { echo "Here you can assemble squads"; } ?></a></h2>
	<div class="post">
		<h3 class="post-title">Create squad</h3>
		<p class="post-time">You have: <span><?php echo $squad['squads']; ?> </span>squads</p>
		<div class="entry">
			<p>Creating squads are vital part of this game. In order to explore the battlefield, you must have
			at least one squad assembled. To assemble an squad, you must choose 5 units, and then create
			squad. 
			When you are making squad, try to make it as effective as possiple. Make sure you have medic
			in squad, so less soldiers will die in fight, they get wounded instead.</p>
				<form action="squads.php?action=create_squad" method="post">
				How many special forces units you wish to put in squad?
				<input type="text" name="create_squad_unit_specforce" /> <b>You have:</b> <?php echo $player['unit_specforce']; ?>
				<br />
				<br />
				How many sniper units you wish to put in squad?
				<input type="text" name="create_squad_unit_sniper" /><b>You have:</b> <?php echo $player['unit_sniper']; ?>
				<br />
				<br />
				How many assault units you wish to put in squad?
				<input type="text" name="create_squad_unit_assault" /> <b>You have:</b> <?php echo $player['unit_assault']; ?>
				<br />
				<br />
				How many support units you wish to put in squad?
				<input type="text" name="create_squad_unit_support" /> <b>You have:</b> <?php echo $player['unit_support']; ?>
				<br />
				<br />
				How many engineer units you wish to put in squad?
				<input type="text" name="create_squad_unit_engineer" /> <b>You have:</b> <?php echo $player['unit_engineer']; ?>
				<br />
				<br />
				How many medic units you wish to put in squad?
				<input type="text" name="create_squad_unit_medic" /> <b>You have:</b> <?php echo $player['unit_medic']; ?>
				<br />
				<br />
				How many anti-tank units you wish to put in squad?
				<input type="text" name="create_squad_unit_antitank" /> <b>You have:</b> <?php echo $player['unit_antitank']; ?>
				<br />
				<br />
				<input type="submit" name="action_create_squad" value="Create squad" />
				<br />
				<br />
				</form> 
		</div>
	</div>
</div>

<?php include("footer.php"); ?>

 

Link to comment
Share on other sites

Here is one suggestion I have for you. To save time, I'm going to just create an array with the POST keys so that we only check the 7 unit types.

 

$validPostKeys = array("create_squad_unit_specforce","create_squad_unit_sniper","create_squad_unit_assault","create_squad_unit_support","create_squad_unit_engineer","create_squad_unit_medic","create_squad_unit_antitank");

 

Now, loop through the POST data with the foreach loop. I'll also try and explain in simple terms what it does.

 

foreach($_POST as $key => $value){
if(in_array($key, array_keys($validPostKeys))){
	for($i = 0; $i < $value; ++$i){
		$units[] = $validPostKeys[$key];
	}
}
}

print_r($units);

 

Ok, so a foreach loop does exactly what it says, it will loop through an array for each element. So if there are 5 elements in your array, it'll loop over them all and perform the same code on each one.

 

So the first parameter is your array, the 2nd is your key variable. If your unsure of arrays. Keys are how you access an array. They can either be numbers (indexed) or letters/words (associative). The 3rd variable is not required, but it is your value variable.

 

Hopefully that clears a little bit up about it.

 

Now as you can see from the code I posted above, it will loop through all the elements of the $_POST array. It then checks the keys of the $_POST array to make sure they are valid (that is so it doesn't try and do the submit button). Then finally, it runs a for loop to insert the correct number of elements into the $units array.

 

Hopefully my explanations have made sense.

 

If you need further help, I'll be around.

 

Regards.

Link to comment
Share on other sites

I did some cleanup on your script, to make it smaller, and should be quicker.

<?php
require_once('auth.php');
require_once('functions.php');
require_once('costs.php');

//Hehehe
$login = "Ardivaba";

$result = mysql_query("SELECT * FROM squads WHERE user='$login'")or die(mysql_error());
$player = mysql_fetch_array( $result );
include("header.php");
$error = 0;
if($_GET["action"] == "create_squad"){
$sqad_slots[] = (int)$_POST["create_squad_unit_specforce"];
$sqad_slots[] = (int)$_POST["create_squad_unit_sniper"];
$sqad_slots[] = (int)$_POST["create_squad_unit_assault"];
$sqad_slots[] = (int)$_POST["create_squad_unit_support"];
$sqad_slots[] = (int)$_POST["create_squad_unit_engineer"];
$sqad_slots[] = (int)$_POST["create_squad_unit_medic"];
$sqad_slots[] = (int)$_POST["create_squad_unit_antitank"];
$create_squad_units = array_sum($sqad_slots);
if($create_squad_units > 5){
	$teade = "You can't have that many units in squad!";
	$error = 1;
}
if($squad_slots[0] > $player['unit_specforce']){
	$teade = "You dont have that many Special Force units!";
	$error = 1;
}

if($squad_slots[1] > $player['unit_sniper']){
	$teade = "You dont have that many Sniper units!";
	$error = 1;
}

if($squad_slots[2] > $player['unit_assault']){
	$teade = "You dont have that many Assault units!";
	$error = 1;
}

if($squad_slots[3] > $player['unit_support']){
	$teade = "You dont have that many Support units!";
	$error = 1;
}

if($squad_slots[4] > $player['unit_engineer']){
	$teade = "You dont have that many Engineer units!";
	$error = 1;
}

if($squad_slots[5] > $player['unit_medic']){
	$teade = "You dont have that many Medic units!";
	$error = 1;
}

if($squad_slots[6] > $player['unit_antitank']){
	$teade = "You dont have that many Anti-Tank Force units!";
	$error = 1;
}

if($error != 1){
	$units = array();
	foreach ($sqad_slots as $key=>$value){
		switch ($key){
			case 0:
				$name = "Special Force";
				break;
			case 1:
				$name = "Sniper";
				break;
			case 2:
				$name = "Assault";
				break;
			case 3:
				$name = "Support";
				break;
			case 4:
				$name = "Engineer";
				break;
			case 5:
				$name = "Medic";
				break;
			case 6:
				$name = "Anti-Tank";
				break;
			default:
				$name = "Invalid";
		}
		echo "Unit $name: $value<br />";
	}
}
}
?>

<?php include("side.php"); ?>

<div id="main">
<p class="user-links"><a href="#">Register now</a> - <a href="#">Forgot
password</a></p>
<p class="time">Money: <span><?php echo $player['money']; ?></span></p>
<div id="content">
<h2 class="cat"><a name="help_text" href="#help_text"><?php if(isset($teade)) { echo $teade; } else { echo "Here you can assemble squads"; } ?></a></h2>
<div class="post">
<h3 class="post-title">Create squad</h3>
<p class="post-time">You have: <span><?php echo $squad['squads']; ?> </span>squads</p>
<div class="entry">
<p>Creating squads are vital part of this game. In order to explore the
battlefield, you must have at least one squad assembled. To assemble an
squad, you must choose 5 units, and then create squad. When you are
making squad, try to make it as effective as possiple. Make sure you
have medic in squad, so less soldiers will die in fight, they get
wounded instead.</p>
<form action="squads.php?action=create_squad" method="post">How many
special forces units you wish to put in squad? <input type="text"
name="create_squad_unit_specforce" /> <b>You have:</b> <?php echo $player['unit_specforce']; ?>
<br />
<br />
How many sniper units you wish to put in squad? <input type="text"
name="create_squad_unit_sniper" /><b>You have:</b> <?php echo $player['unit_sniper']; ?>
<br />
<br />
How many assault units you wish to put in squad? <input type="text"
name="create_squad_unit_assault" /> <b>You have:</b> <?php echo $player['unit_assault']; ?>
<br />
<br />
How many support units you wish to put in squad? <input type="text"
name="create_squad_unit_support" /> <b>You have:</b> <?php echo $player['unit_support']; ?>
<br />
<br />
How many engineer units you wish to put in squad? <input type="text"
name="create_squad_unit_engineer" /> <b>You have:</b> <?php echo $player['unit_engineer']; ?>
<br />
<br />
How many medic units you wish to put in squad? <input type="text"
name="create_squad_unit_medic" /> <b>You have:</b> <?php echo $player['unit_medic']; ?>
<br />
<br />
How many anti-tank units you wish to put in squad? <input type="text"
name="create_squad_unit_antitank" /> <b>You have:</b> <?php echo $player['unit_antitank']; ?>
<br />
<br />
<input type="submit" name="action_create_squad" value="Create squad" />
<br />
<br />
</form>
</div>
</div>
</div>

<?php include("footer.php"); ?>

You will notice I explicitly set the $_POST values to integers, as well as pushing the POST to an array.  Arrays are easier to work with when you are doing a foreach loop.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.