I'm working with an existing foreach that is stepping through an array of values pulled from the database. I'd like to perform some logic based on each key/value pair and assign some values to variables to output as part of the foreach loop.
Specifically I need to output the availability as determined based on some values for each key/pair. My logic works, but the value of the last record is assigned to EVERY record that passes the conditional tests, even if the values are different.
How can I assign $value['availability'] correctly for each time through the loop?
Here's my code:
foreach ($prices as $value) {
if(!$this->_validateAttributeValue($attributeId, $value, $options)) {
continue;
}
$currentProduct->setConfigurablePrice(
$this->_preparePrice($value['pricing_value'], $value['is_percent'])
);
$currentProduct->setParentId(true);
Mage::dispatchEvent(
'catalog_product_type_configurable_price',
array('product' => $currentProduct)
);
$configurablePrice = $currentProduct->getConfigurablePrice();
if (isset($options[$attributeId][$value['value_index']])) {
$productsIndex = $options[$attributeId][$value['value_index']];
} else {
$productsIndex = array();
}
/* Check the quantity */
if($options['qty'][$value['label']] <= 0) {
if ($product->getResource()->getAttribute('item_status')->getFrontend()->getValue($product) == "Preorder") { // Preorder
$value['availability'] = "Pre-order";
}
elseif ($product->getResource()->getAttribute('item_status')->getFrontend()->getValue($product) != "Discontinued") { // Must be an active backorder item
if ($product->getResource()->getAttribute('new_availability')->getFrontend()->getValue($product) != "No") {
$value['availability'] = $product->getResource()->getAttribute('new_availability')->getFrontend()->getValue($product);
}
else {
$value['availability'] = "Temporarily out of stock";
}
}
}
$info['options'][] = array(
'id' => $value['value_index'],
'label' => ($options['qty'][$value['label']] <= 0) ? $value['label'] . ': '.$value['availability'].'' : $value['label'] . ": In stock",
'price' => $configurablePrice,
'oldPrice' => $this->_prepareOldPrice($value['pricing_value'], $value['is_percent']),
'products' => $productsIndex,
);
$optionPrices[] = $configurablePrice;
}
Try
foreach ($prices as $key=>$value){
//your code
}
Related
In this project i have a multidimentional array that keeps some employees names, their position, their speciality and their salary. I need to find the average salary of all the managers and all the employees from the array.
<!DOCTYPE html>
<html>
<head>
<meta sharset="UTF-8"/>
<title>Project3</title>
</head>
<body>
<?php
$employees = array(array("name" => "Nikolaou Nikolaos",
"occupation" => "Employee",
"salary" => 1500,
"specialty" => "Web Programmer"),
array("name" => "Papadopoulou Anna",
"occupation" => "Manager",
"salary" => 2300,
"specialty" => "Human resources management"),
array("name" => "Alexiou Nikoleta",
"occupation" => "Employee",
"salary" => 800,
"specialty" => "Secretary"),
);
//Start of the function that prints the arrays in a specific way.
function printTable($table)
{
foreach ($table as $employee => $list) {
// Print a heading:
echo "<h2 style=\"text-align:left; font-size:26px; font-family:times new roman; color:blue\">Employee #$employee</h2><ul>";
// Print each district data:
foreach ($list as $key => $value) {
echo "<li style=\"text-align:left; font-size:18px; font-family:times new roman; color:black\">$key: $value</li>\n";
}// End of nested FOREACH.
// Close the list:
echo '</ul>';
} // End of main FOREACH.
}// End of the function.
//function that calculates and returns the average salary of employees and managers separately.
function calcMeanAges($table, &$hmean, &$gmean)
{
$cEmployees = 0;
$sumsalary_e = 0;
$cManagers = 0;
$sumsalary_m = 0;
foreach ($table as $occupation =>$list) {
foreach ($list as $salary =>$value) {
if ($occupation == "Employee") {
$cEmployees++;
$sumsalary_e += $salary['salary'];
}
if ($occupation == "Manager") {
$cManagers++;
$sumsalary_m += $salary['salary'];
}
}
}
$hmean = $sumsalary_e / $cEmployees;
$gmean = $sumsalary_m / $cManagers;
}
//call of the function that calculates the average salaries.
calcMeanAges($employees, $h, $g);
echo "$h<br>";
echo "$g";
//Printing the elements of the arrays
echo '<p style="color:red;font-size:28px;font-family:times new roman;"><b>Employees and managers</b></p><br>';
printTable($employees);
?>
</body>
</html>
I need to calculate the average salaries of employees and managers separately. So i thought of putting a condition in the Foreach() to check who is who and then count them and keep the sum of their salary. But it doesn't work properly. I would appreciate some help.
Basically:
To calculate the average sum up all different figures and then divide them through the total amount of figures.
So this part should be right.
Can you please check the datatypes of each from them:
$hmean = $sumsalary_e / $cEmployees;
$gmean = $sumsalary_m / $cManagers;
Every type should be an Integer or Int.
You only need one loop not 2 in this case, then all the occurances you want to check or dd up are members of the inner arrays
function calcMeanAges($table, &$hmean, &$gmean)
{
$cEmployees = 0;
$sumsalary_e = 0;
$cManagers = 0;
$sumsalary_m = 0;
foreach ($table as $item) {
if ($item['occupation'] == "Employee") {
$cEmployees++;
$sumsalary_e += $item['salary'];
}
if ($item['occupation'] == "Manager") {
$cManagers++;
$sumsalary_m += $item['salary'];
}
}
$hmean = $sumsalary_e / $cEmployees;
$gmean = $sumsalary_m / $cManagers;
}
this will proccess any occuption and calculate avarage salary. You can add an IF statment if you only need managers and Employee. You can leave it as be if at a later state other occuptions are added.
$employees = array(
array("name" => "Nikolaou Nikolaos",
"occupation" => "Employee",
"salary" => 1500,
"specialty" => "Web Programmer"),
array("name" => "Papadopoulou Anna",
"occupation" => "Manager",
"salary" => 2300,
"specialty" => "Human resources management"),
array("name" => "Alexiou Nikoleta",
"occupation" => "Employee",
"salary" => 800,
"specialty" => "Secretary"),
);
function averageCount($employees)
{
$count = [];
foreach ($employees as $employee) {
$occupation = $employee['occupation'];
if (!array_key_exists($occupation, $count)) {
$count[$occupation]['occupation'] = $occupation;
$count[$occupation]['salary'] = $employee['salary'];
$count[$occupation]['count'] = 1;
} else {
$count[$occupation]['salary'] += $employee['salary'];
$count[$occupation]['count']++;
}
}
if (count($count) > 0) {
foreach ($count as $occupation => $item) {
$count[$occupation]['average'] = $item['salary'] / $item['count'];
}
}
return $count;
}
var_dump(averageCount($employees));
i have 1 million data using foreach.
ex table:
table
the data
data
i want to inserting that's data using batch/multipleinsert, but i have problem when i got duplicate data. if data duplicate i want the field amount will sum and update amount field with sum amount duplicated data.
this is my code before
<?php
foreach ($data_transaksi as $key)
{
if($key['STATUS_COA'] != $key['CHART_OF_ACCOUNT_STATUS'])
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2);
}
else
{
$amount = round($key['AMOUNT'],2) *-1;
}
}
else
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2)*-1;
}
else
{
$amount = round($key['AMOUNT'],2);
}
}
$dt_exsis = $this->ledger_model->cek_data_coa_exsis($key['COA_CODE'],$modul,$ID_USER);
if(empty($dt_exsis['id']))
{
//TRYINSERTINGBATCH
// $datainsert[] = '('.$key['COA_CODE'].','.$amount.','.$ID_USER.',"'.$modul.'")';
// $test = $key['COA_CODE'];
$datainput = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
$this->ledger_model->save_rows_to_table($datainput,'finance_lapkue_temp');
}
else
{
$amount_fix = $amount + $dt_exsis['AMOUNT'];
$data=array(
'AMOUNT' => $amount_fix
);
$this->ledger_model->edit_rows_to_table_where($data,'finance_lapkue_temp','id',$dt_exsis['id']);
// $q = "UPDATE finance_lapkue_temp set AMOUNT = '$amount_fix' where id = '".$dt_exsis['id']."'";
// $this->db->query($q);
}
// $data_amount[$key['COA_CODE']] += $amount;
}
?>
if i using this code, the proccess so slow
Good option will to pass only data to DB that you want to insert. All the data cleaning task can be done in controller.
// Create a data array and add all info
$data = [];
//if user does not exist add it in array
if (empty($dt_exist($id))) {
$data[$ID_USER] = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
}
else {
//if user exist in $data just modify the amount
if (!empty($data[$ID_USER])) {
$data[$ID_USER]['AMOUNT'] += $dt_exsis['AMOUNT'];
}
else {
// if user does not exist in data create add all info
$data[$dt_exsis['ID_USER']] = array(
'COA_CODE' => $dt_exsis['COA_CODE'],
'AMOUNT' => $dt_exsis['amount'],
'MODUL' => $dt_exsis['modul'],
'USER_ID' => $dt_exsis['ID_USER']
);
}
}
This will save multiple calls to DB and at the end you can pass $data and do multiple insert.
I'd like to check if array exist by two keys: id and type
This code just check by id:
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
else {
$type = '';
}
if (array_key_exists($id, $_SESSION['cart'])) {
$_SESSION['cart'][$id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$id] = $line;
}
I have tried with this code but it doesn't work:
if (array_key_exists($id, $_SESSION['cart']) && array_key_exists($type, $_SESSION['cart'])) {
$_SESSION['cart'][$id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$id] = $line;
}
$_SESSION['cart'] is an array contains arrays of $line
$line = array(
'id' => $id,
'type' => $type,
'quantity' => $quantity,
'price' => $price,
'picture' => $dish->getPicture()->getWebPath(),
);
This is the output of $_SESSION['cart']:
As you see in th last array with id 55 and type "french bred" , what I'd like to do is to check if th user chose the same product but a with different type so insert new line else if the same product and the same type so just update quantity.
Something like this should do, however the question is too vague and too little code is shown for me to properly understand your problem
$lineExists = false;
foreach($_SESSION['cart'] as $index => $line){
if($line['id'] === $id)
{
$_SESSION['cart'][$index]['quantity'] += $quantity;
$lineExists = true;
}
}
if(!$lineExists)
{
$_SESSION['cart'][] = $newLine;
}
If you want to check if type and id exists then you should do something like this
if (array_key_exists('id', $_SESSION['cart']) && array_key_exists('type', $_SESSION['cart'])) {
// stuff here..
}
if $id is the value of the key id so 'id' => 5 then you should check like this:
if ($_SESSION['cart']['type'] == $id) {
// stuff here
}
Hope this somewhat helps you further!
I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)
Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
i am adding products to session as array but before adding that product to session how to check that product is present in session array or not.
If the product is present i want to increase the count of that product, if not add that product to session array. My php code is given below.
session_start();
if(empty( $_SESSION['fields1'] )) {
$_SESSION['fields1'] = array();
}
$qty = 1;
$id = $_POST['id'];
$name = $_POST['name'];
$description = $_POST['description'];
$cnt = 0;
print_r($_SESSION['fields1']);
if (! empty($_SESSION['fields1'])){
foreach ($_SESSION['fields1'] as $key=>$val){
if ($id == $val['id']){
$qty = $val['qty']++;
//echo "qty ===".$qty;
$_SESSION['fields1'][$cnt]['qty'] = $val['qty']++;
}
else
{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
$cnt++;
}
}else{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
//print_r($_SESSION['fields1']);
echo json_encode($_SESSION['fields1']);
If $id is ID of product and fields is array of products, try something like this:
if(empty($_SESSION['fields'][$id]))
$_SESSION['fields'][$id]['qty'] = 1;
else
$_SESSION['fields'][$id]['qty']++;