loop through same variables in for loop - php

How can I loop through each of these variable within a for loop?
$prod1 = $_POST['Option1']; //get input text
$prod2 = $_POST['Option2']; //get input text
$prod3 = $_POST['Option3']; //get input text
$prod4 = $_POST['Option4']; //get input text
for ($i=1; $i < 5; $i++) {
$prod = $prod . $i;
}
when I echo $prod . $i inside the loop, I want it to display the variable value.

You should be better off with storing your data in an array and then looping over the array:
$products = [
$_POST['Option1'],
$_POST['Option2'],
$_POST['Option3'],
$_POST['Option4']
];
foreach ($products as $prod ) {
echo $prod;
}
Alternatively, You can also iterate over the POST directly:
for ($i=1; $i < 5; $i++) {
echo $_POST['Option' . $i];
}

You can loop through the $_POST variable - it's an array.
foreach ($_POST as $prod)
{
echo $prod;
}
(Obviously if there are other values in the $_POST array then you would need to check the key name first before deciding to use it.)
N.B. We don't know the source of this data (is it a HTML form) but it might make more sense for them to be submitted inside a single array to begin with - so all of the values would be accessed through $_POST["options"] for example, and you'd just loop through that specific list.

Related

Sort array output

$runrwos = array();
for ($i = 0; $runrwos= mysql_fetch_assoc($run); $i++)
{
$DD_E_SC[$i]=$runrwos['DD_E_SC'];
$DD_E_pKW[$i]=$runrwos['DD_E_pKW'];
$DD_G_SC[$i]=$runrwos['DD_G_SC'];
$DD_G_pKW[$i]=$runrwos['DD_G_pKW'];
$data[$i] = array('DD_E_SC'=>$runrwos['DD_E_SC'],'DD_E_pKW'=>$runrwos['DD_E_pKW'], 'DD_G_SC'=>$runrwos['DD_G_SC'], 'DD_G_pKW'=>$runrwos['DD_G_pKW']);
foreach ($data as $entry)
{
$Ep =($entry['DD_E_SC']*365+$entry['DD_E_pKW']*$SE_cons )/100;
$Gp =($entry['DD_G_SC']*365+$entry['DD_G_pKW']*$SG_cons )/100;
$Tp=$Ep+$Gp;
}
}
I have the above code that get row data from a database, once data are retrieved and stored into an array give the expected result.
This code work fine, but output result as retrieved from database.
My problem is when I sort the data by $Tp or $Ep or $Gp.
I need to sort by descendant or ascendant value.
Any help Thanks

PHP storing a two dimension array from MySQL query

I have a simple question. I have an array that has two columns (id, name) that is a result of a MySQL query. I want to store the result of the query into a array variable so i can access each element when i need to.
I am able to store a one dimension array like the following:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row['name'];
}
How can I store and access a two dimensional array? Also is it best to use a for loop or while loop to store these?
Simply do this:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
To access your results you can do this:
$firstResultRow = $array[0];
$firstResultName = $array[0]['id'];
$firstResultName = $array[0]['name'];
This will tell you if a particular row exists:
if(isset($array[$x])) {
$aRow = $row[$x];
// do stuff with $aRow;
}
This will give you a row count for your array:
$rowCount = count($array);
This will set up a loop through your array:
foreach($array as $index => $row) {
$id = $row['id']
$name = $row['name'];
// $index will have the array index of the current row. 0 -> $rowCount - 1
}
Don't specifically store the index of $row but rather store the whole row.
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
Then $array will have the following structure:
$array = [
[
'id'=> ...,
'name' => ...,
],
...
];
To initially access all of the results from [mysqli_fetch_assoc][1] you will want to use the while loop like you are, mysqli_fetch_assoc will continue to output results until it doesn't have any more data. Then at that point mysqli_fetch_assoc will return NULL. This will signal to your while loop to stop iterating.
Then to access variables inside of your $array, I recommend using foreach.
You could then do:
foreach ($array as $row) {
do something with $row['name'] or $row['id']
}
You could also use a for loop, but it takes more work IMO. Compare the above with this alternative:
for ($i = 0; $i < count($array); $i++) {
$row = $array[$i];
do something with $row['name'] or $row['id']
}

str_replace within a while loop - PHP

I'm having a problem with str_replace within a while loop.
I've created a couple of variables before a while loop:
$c = 0; // This represents the first object within an array EG: array[0]
$i = 1; // This represents the first [image#] tag within $articleContent
What I'm trying to achieve is, when the user inputs '[image1], [image2], [image3]' etc into the $articleContent, to replace the [image#] tags with an <img src=""/> containing the file path located within the unserialized array.
The $images[$c] variable is pointing to the file path with the id of [0] within the array.
The issue:
My expectations were that the loop would naturally count through each $c and $i, labeling each [image#] and array object accordingly, then replacing the [image#] tag with the <img src='images/$imageSplit[$i]'/>, however this has not been the case.
The current functionality:
Say I have three articles being echo'd by the loop. each with three [image#] tags in [image1], [image2] and [image3]. The first article will ONLY show the first image, the second article will only show the second image, and the third article will only show the third.
If anyone could point me in the right direction for the script to replace the image tags accordingly then that'd be much appreciated.
Here is my code so far:
$sql = "SELECT * FROM articles";
$res = mysql_query($sql);
$i = 1; // [image#]
$c = 0; // Array object #
echo "<br/><br/>";
while($row = mysql_fetch_assoc($res)){
$title = $row['title']; // Grabs the title
$articles = $row['articleContent']; // Grabs the article
$images = unserialize(base64_decode($row['image']));
$imageSplit[$i] = $images[$c]; // [image1] = array[0]
$articles = str_replace("[image$i]","<img src='images/$imageSplit[$i]' width='300px' height='auto'/>","$articles");
// str_replace is only applied once per loop
echo "Title: $title<br/>
Content: $articles<br/>
c = $c<br/>
i = $i<hr/>";
// All variables, including $c and $i are both echoing out correctly, however $i is only being applied correctly once every loop
$c++;
$i++;
}
Say I have three articles being echo'd by the loop. each with three
[image#] tags in [image1], [image2] and [image3]
That means you will have to nest 2 loops: a)foreach article, b)foreach one of its images.
Here is a possible way of doing it (I commented out some of the lines that won't be needed):
$sql = "SELECT * FROM articles";
$res = mysql_query($sql);
//$i = 1; // [image#]
//$c = 0; // Array object #
echo "<br/><br/>";
while($row = mysql_fetch_assoc($res)){
$title = $row['title']; // Grabs the title
$articles = $row['articleContent']; // Grabs the article
$images = unserialize(base64_decode($row['image']));
// $imageSplit[$i] = $images[$c]; // [image1] = array[0]
foreach ($images as $index => $img_url) {
$i = $index + 1;
$articles = str_replace("[image$i]","<img src='images/$img_url' width='300px' height='auto'/>","$articles");
}
echo "Title: $title<br/>
Content: $articles<br/>
<br/>
<hr/>";
// All variables, including $c and $i are both echoing out correctly, however $i is only being applied correctly once every loop
//$c++;
//$i++;
}

Get a field from an Array of records

How do I get all the values from a field in a record in an Array?
I want to make an average from a numerical score held under a specific field in an Array. The array is pulled from a form. Here is what I have so far but it just doesn't work.
$records = get_field('maths_month_report'); //gets all the records
$progressscore = $records['progress']; //targets the specific field in those records
echo . array_sum($progressscore)/count($progressscore) .; //divides the numbers in the field by the amount of records
revision: My apologies for not mentioning that the records are Arrays within the 'maths_month_report' Array. I can target specific fields in specific records with:
$firstrecord = $records[0];
$output = $firstrecord['progress'];
I just want to target all the 'progress' values so i can average them.
Based on your comments, if these are arrays within an array, you would need to build a new array:
$progresscore = array_column($records, 'progress')
PHP < 5.5:
$progresscore = array_map(function($item) {
return $item['progress'];
}, $records);
Or, just iterate yourself:
$sum = $count = 0;
foreach ($records as $record) {
$sum += $record['progress'];
++$count;
}
echo $sum / $count;

An array value empty although previously populated

Hi I'm am sure this is a silly mistake but I have been staring at this the past 20mins to
no avail. I have an array balance[] that is populated with two values for balance[0]
and balance[1]. These are populated within the first for loop however when I go to use these values outside after this the array balance[0] is empty.
Below is my code and output:
for ($i=0; $i<$counter; $i++){
$x = mysql_query("
SELECT `outputValue` FROM `output` WHERE `outputType`= 'balance' && `period`= '6' && teamID = '$ID[$i]'
")or die($x."<br/><br/>".mysql_error());
// set ID's = to a variable and now get Outputs for each variable(teamID)
$balance = array();
$row = mysql_fetch_assoc($x);
echo $i." = I<br/>";
$balance[$i] = $row['outputValue'];
echo "Team ".$i."Balance = ".$balance[$i]."<br/>";
}
for ($i=0; $i<$counter; $i++){
echo "Team ".$i."Balance = ".$balance[$i]."<br/>";
}
You're initializing the $balance inside of the loop. On each for loop iteration, the $balance value is rewritten with an empty array().
On the first iteration, the $balance is set to an empty array, and then the $balance[0] is set.
On the second iteration, the $balance is set to an empty array again, and then the $balance[1] is set.
So, after the loop, the $balance will only contain one element at the index of $counter-1.
Move the line
$balance = array();
outside of the loop.

Categories