I was given to fill this html table according to this multidimensional array.
$eleves=array(
"Z200"=>array(
"Salima",
"module"=>array(
"Math"=>array("note"=>10,"cof"=>5),
"Physique"=>array("note"=>10,"cof"=>2),
"Langue"=>array("note"=>10,"cof"=>2)
)
),
"Z103"=>array(
"Ali",
"module"=>array(
"Math"=>array("note"=>2,"cof"=>5),
"Physique"=>array("note"=>5,"cof"=>2),
"Langue"=>array("note"=>7,"cof"=>2)
)
),
"Z109"=>array(
"Hind",
"module"=>array(
"Math"=>array("note"=>13,"cof"=>2),
"Physique"=>array("note"=>13,"cof"=>2),
"Langue"=>array("note"=>11# ,"cof"=>2)
)
)
);
I tried the foreach loop. I succeed to fill the first head tables.
But when it comes to calculate the notes it's diffcult to call the values
Can you help me guys please ?
You need a first foreach to browse $eleves. For each student, you need a second foreach to add all grades and evaluate the mean.
function evalMoyenne ($grades) {
$gradeSum = 0;
$coeffCount = 0;
foreach ( $grades as $subject => $grade ) {
$gradeSum += $grade['note'] * $grade['cof'];
$coeffCount += $grade['cof'];
}
return $gradeSum / $coeffCount;
}
foreach ( $eleves as $matricule => $row ) {
$moyenne = evalMoyenne( $row['module'] );
echo "<td>$matricule</td>"
. '<td>' . $row[0] . '</td>'
. '<td>' . $moyenne . '</td>'
}
Usually, if you have an array in an array, you need a foreach in a foreach. As an alternative, if there are a fixed subject count, you could also hardcode the meaning calculation:
$gradeSum = $row['module']['Math']['note'] * $row['module']['Math']['cof']
+ $row['module']['Physique']['note'] * $row['module']['Physique']['cof']
+ $row['module']['Langue']['note'] * $row['module']['Langue']['cof']
$cofSum = $row['module']['Math']['cof'] + $row['module']['Physique']['cof'] + $row['module']['Langue']['cof'];
$moyenne = $gradeSum / $cofSum;
Related
I am trying to make an e-commerce website and I can't quite figure out how to get the cart to function. I am able to add amounts to the cart before purchase but I want it to delete the item from the cart when the quantity is set to 0.
if (isset($_POST['update'])) {
for ($i = 0; $i < sizeof($_SESSION['quantity']); $i++) {
$postID = 'qty' . $i;
$_SESSION['quantity'][$i] = $_POST[$postID];
if ($_SESSION['quantity'][$i] == 0) {
unset($_SESSION['shoppingcart'][$i]);
unset($_SESSION['quantity'][$i]);
unset($_SESSION['name'][$i]);
unset($_SESSION['price'][$i]);
}
}
}
Here is the cart variable that creates a table of all the products added
<form method="post">
<?php
if (!empty($_SESSION['shoppingcart'])) {
for ($i = 0; $i < sizeof($_SESSION['shoppingcart']); $i++) {
$cart .= '<tr>';
$cart .= '<td>' . $_SESSION['name'][$i] . '</td>';
$cart .= '<td><input type="text" id="quantity"name="qty' . $i . '"value="' . $_SESSION['quantity'][$i] . '" onkeyup="checkInput()"></td>';
$cart .= '<td>$' . $_SESSION['price'][$i] . '</td';
$cart .= '<td>$' . $_SESSION['quantity'][$i] * $_SESSION['price'][$i] . '</td>';
$cart .= '</tr>';
$total += ($_SESSION['quantity'][$i] * $_SESSION['price'][$i]);
$totalDiscounted += ($_SESSION['quantity'][$i] * $_SESSION['price'][$i]) / 100 * 30;
}
</form>
This works when I delete things going from the last piece in the array, going to the first thing added in the array in that order, but when I try to delete the first element or anything out of order first, it gives me an error. "Warning: Undefined array key 0". What am I doing wrong?
The undefined index come from the use of unset(). The indexes of the array will not be re-ordered after unset() call.
Exemple:
$array = [1, 2, 3];
unset($array[1]);
print_r($array); // indexes : 0 and 2.
You could:
use array_values() to re-index arrays.
unset($_SESSION['shoppingcart'][$i]);
$_SESSION['shoppingcart'] = array_values($_SESSION['shoppingcart']);
or, check the presence of the data in the loop :
for ($i = 0; $i < sizeof($_SESSION['shoppingcart']); $i++) {
if (!isset($_SESSION['name'][$i])) {
continue;
}
$cart .= '<tr>';
//...
}
Another way is to use a data structure for the order:
// add
$_SESSION['shoppingcart'][] = [
'quantity' => 1,
'name' => 'item',
'price' => 1.00,
];
// to update an index
$_SESSION['shoppingcart'][$index]['quantity'] = 2;
// to remove an index
unset($_SESSION['shoppingcart'][$index]);
then, use a foreach() to list
foreach ($_SESSION['shoppingcart'] => $data) {
// display item
}
I'm currently updating the database with selected values, however, I am using a for loop to process for each entry. But I can only do this to a select number, currently 6 as shown below.
for ($ind = 0; $ind <6; $ind++ )
How would I make it loop through all & then stop?
I'm currently getting the values from another page using $_POST & then submitting them to the database on this page. As shown below:
for ($ind = 0; $ind <6; $ind++ ) {
$SID = $_POST['SID' . $ind];
$week1 = $_POST ['week1' . $ind];
$week2 = $_POST ['week2' . $ind];
$week3 = $_POST ['week3' . $ind];
$week4 = $_POST ['week4' . $ind];
$week5 = $_POST ['week5' . $ind];
$week6 = $_POST ['week6' . $ind];
$week7 = $_POST ['week7' . $ind];
$week8 = $_POST ['week8' . $ind];
$week9 = $_POST ['week9' . $ind];
$week10 = $_POST ['week10' . $ind];
$sqlQuery = "Update weekbyweek SET Week_1=".$week1.", Week_2=".$week2.", Week_3=".$week3.", Week_4=".$week4.", Week_5=".$week5.", Week_6=".$week6.", Week_7=".$week7.", Week_8=".$week8.", Week_9=".$week9.", Week_10=".$week10." WHERE SID='".$SID."'";
$statement = $db->prepare($sqlQuery);
$statement->execute(['$Week_1' => $week1, '$Week_2' => $week2,'$Week_3' => $week3, '$Week_4' => $week4,'$Week_5' => $week5, '$Week_6' => $week6,'$Week_7' => $week7, '$Week_8' => $week8,'$Week_9' => $week9, '$Week_10' => $week10]);
}
Use foreach loop instead of for. The foreach loop is mainly used for looping through the values of an array.
<?php
foreach (array as $value) {
// Code to be executed;
}
You can set a count that will check the length of your data array.
Below will loop 8 times and then stop.
In below case the data is an array. If working with databaseso you would have to query the database for the X amount setting that you would need, stored the result in a variable and set the count to that variable value.
$data = [0,1,2,3,4,5,6,7];
for ($i=0; $i <= count($data) ; $i++) {
// code...
}
Use this:
$items = [1,2,3,4,5,6,7];
if( !empty( $items ) ){
for ( $i=0; $i < count( $items ) ; $i++ ) {
//code here
}
}
Or
foreach( $items as $item ){
//code here
}
I am trying to make a query where I want to retrieve items querying a field in the database.
I need to check something as follows (example):
To retrieve books where the text field contain "Soccer" or "Basketball":
I want to have the items where only in the population above:
contain '1989'
and
exclude 'Europe'
Any idea? I am doing a counting for now but it does not work:
//search words
foreach ($cardSearch as $value) {
$regexSearch[]['text'] = new MongoRegex("/" . $value . "/");
}
//words included
foreach ($cardInclu as $value) {
$regexInclu[]['text'] = new MongoRegex("/" . $value . "/");
}
//words excluded
foreach ($cardExlu as $value) {
$regexExclu[]['text'] = new MongoRegex("/" . $value . "/");
}
$arr['$and'] = $regexInclu;
$arr['$ne'] = $regexExclu;
array_push($regexSearch, $arr);
$i = $mongoCollection->count(array('$or' => $regexSearch));
or
$i = $mongoCollection->count(array('$or' => $regexSearch,
'$and' => $regexInclu, '$ne' => $regexExclu));
Thanks!
I'm pulling 3 colummns from one table and storing them in an array as such to populate a dropdown menu. The ref_code is used to decide which dropdown it will go to ('Module','Customer','Application') while id is the select value and ref_desc is the display text.
foreach ($test as $t) {
$aa[] = array($t->ref_code => array('id'=>$t->id, 'ref_desc'=>$t->ref_desc));
};
I've been trying to retrieve them using $aa['ref_code'] but have not been getting any success. Help please.
This question is similar, but I am unable to retrieve the values I want.
I found a solution on another forum but I will also give your solutions a try later. Thank you very much!
foreach ($aa as $a => $d) {
foreach ($d as $ref_code => $dd) {
echo "<p>". $ref_code ."</p>";
echo "<p>". $dd['ref_desc'] ."</p>";
echo "<p>". $dd['id'] ."</p>";
};
};
Why don't you write it like this? The ref_code (if it's unique) is the key of the array.
foreach ($test as $t) {
$aa[$t->ref_code] = array('id'=>$t->id, 'ref_desc'=>$t->ref_desc);
};
you need a three dimensional array:
dropdown => ids => displaytext
here we go:
// fill in:
$aa = array();
foreach ($test as $t) {
if ( !isset($aa[$t->ref_code]) )
$aa[$t->ref_code] = array();
$aa[$t->ref_code][$t->id] = $t->ref_desc;
};
// have a drop down:
$myDropDown = 'Customer';
foreach ( $aa[$myDropDown] as $id => $displaytext )
{
echo "<option value=\"" . $id . "\">" . $displaytext . "</option>";
}
.... etc.
I'm using the following code to validate a 'set' of input fields. 4 fields per set (width/height/length/weight). If a set of my input fields are empty then it won't display that row of data in my final $all variable.
Here is a previous topic on the subject: Removing Data from Variable if Input Fields incomplete - PHP - this works great.
However, this time I am using "Placeholder" text (input field value attribute) and therefore I need my PHP to check whether that placeholder value exists.
Here is my Pseudo Code, however I'm unsure how to achieve with regular PHP:
if ((pNUM-VALUEheight = "Height (cm)" OR pNUM-VALUEwidth = "Width (cm)" OR pNUM-VALUElength = "Length (cm)" OR pNUM-VALUEweight = "Weight (kg)"))
Then
// Don't store in $all variable
Else
// Do store set of values in $all variable
End If
Here is my current PHP code:
...
$ierrors = array();
$all = '';
// Loop over the values 1 through 20
foreach( range( 1, 20) as $i)
{
// Create an array that stores all of the values for the current number
$values = array(
'p' . $i . 'height' => $_POST['p' . $i . 'height'],
'p' . $i . 'width' => $_POST['p' . $i . 'width'],
'p' . $i . 'length' => $_POST['p' . $i . 'length'],
'p' . $i . 'weight' => $_POST['p' . $i . 'weight']
);
// Assume all values are empty.
$allEmpty = true;
// Validate every value
foreach( $values as $key => $value)
{
if( empty($value))
$ierrors[] = "Value $key is not set";
else
$allEmpty = false;
// You can add more validation in here, such as:
if( !is_numeric( $value) )
$ierrors[] = "Value $key contains an invalid value '$value'";
}
// Join all of the values together to produce the desired output
if (!$allEmpty)
$all .= implode( '|', $values) . "\n\n";
}
...
Many thanks for any pointers here or please let me know if any clarity is needed.
Thank you
As you're using jQuery, I'd use a bit of JavaScript to clear the input fields on submit:
$('form').submit(function() {
$(this).find('input[type=text]').each(function() {
var domElement = $(this).get(0);
if (domElement.value == domElement.defaultValue) {
domElement.value = '';
}
});
});
Watch out for typos, didn't test.
You can then check in your PHP file for empty strings and don't have to explicitly state all the possible values (they might change slightly, after all):
if ($_POST['inputName'] == '')
OR
you could use a simple for loop:
for ($i = 0, $numFields = 20; $i <= $numFields; ++$i) {
if ($_POST['p' . $i . 'width'] != 'Width (cm)' && $_POST['p' . $i . 'height'] != 'Height (cm)') {
// add row to table
}
}
What about doing something like this with your HTML:
<input type="text" name="length[]">
<input type="text" name="width[]">
Then you can do something like this in PHP:
if(array_keys($_POST['length']) != array_keys($_POST['width']))
{
// Incomplete post
}
$all_keys = array_merge(array_keys($_POST['length']), array_keys($_POST['width']));
foreach($all_keys as $curr_key)
{
// $_POST['length'][$curr_key]
// $_POST['width'][$curr_key]
}
While using JS is good to validate information from the client before submission. You should always check your values server side as well.