I have a problem with showing results in search engines. It takes 8 seconds to search results to show. It is very long and does not make sense.
Is there a way to get a small part of the results displayed immediately (eg. displaying pages 1 and 2 separately), and the rest a few seconds later?
This is my code:
public function index($destination_main_id=null,$accommod_main_id=null,$search_period_code=null,$total_person=null,$pageNum=null, $order=null, $range_days=null){
//post podaci filtriranja
//print_r($_POST['filter']);
if(!empty($_POST['filter'])){
$this->set('ajax_load',1);
}else{
$this->set('ajax_load',0);
}
//inicijacija varijabli
if(!empty($_POST['radio1'])){
$this->request->data['SearchEngine']['accommod_main_id']=$_POST['radio1'];
}
if($order==''){
$order='asc';
}
if($range_days==''){
$range_days=0;
}
//search period
if(!$search_period_code){
$search_period=$this->Calendar->getDatesBetweenDates($this->request->data['SearchEngine']['arrival'], $this->request->data['SearchEngine']['departure']);
$search_period_code = base64_encode(serialize($search_period));
}else{
$search_period = #unserialize(base64_decode($search_period_code));
}
$count_search_period=count($search_period);
//destination
if(!empty($this->request->data['SearchEngine']['destination_main_id'])){
$destination_main_id=$this->request->data['SearchEngine']['destination_main_id'];
}
//accommodation type
if(!empty($this->request->data['SearchEngine']['accommod_main_id'])){
$accommod_main_id=$this->request->data['SearchEngine']['accommod_main_id'];
}
//person calculation
if(!empty($this->request->data['SearchEngine']['adults']) OR !empty($this->request->data['SearchEngine']['children1']) OR !empty($this->request->data['SearchEngine']['children2']) OR !empty($this->request->data['SearchEngine']['baby']) ){
if($this->request->data['SearchEngine']['baby']>=3){
$total_baby=round($this->request->data['SearchEngine']['baby']/3);
}else{
$total_baby=0;
}
$total_person=$this->request->data['SearchEngine']['adults']+$this->request->data['SearchEngine']['children1']+$this->request->data['SearchEngine']['children2']+$total_baby;
}
//+/- radio raspon
if(!empty($this->request->data['SearchEngine']['days'])){
$range_days=$this->request->data['SearchEngine']['days'];
}
//display accommodation units
if(!empty($_POST['filter']))
{
$AccommodUnits=$this->AccommodUnit->getAllFilterUnits($total_person,$destination_main_id,$_POST['filter'],$this->lang);
}else{
$AccommodUnits=$this->AccommodUnit->getAllUnits($total_person,$destination_main_id,$this->lang);
}
//display accommodation objects
$AccommodObjectIds1=array();
$AccommodMainAccommodObjects=$this->AccommodMainAccommodObject->find('all',array('conditions' => array('AccommodMainAccommodObject.accommod_main_id' => $accommod_main_id),'order' => array('AccommodMainAccommodObject.accommod_object_id')));
foreach($AccommodMainAccommodObjects as $current1){
$this->AccommodObject->locale = $this->lang;
$this->AccommodObject->recursive = -1;
$AccommodObject=$this->AccommodObject->find('first',array('conditions' => array('AccommodObject.id' => $current1['AccommodMainAccommodObject']['accommod_object_id'],'AccommodObject.active' => '1')));
if(!empty($AccommodObject['AccommodObject']['id'])){
$AccommodObjectIds1[]=$AccommodObject['AccommodObject']['id'];
}
}
//filtriranje by objects
$AccommodObjectIds3=array();
if( !empty($_POST['filter']['benefit']) ){
foreach($AccommodObjectIds1 as $current10){
$AccommodObject=$this->AccommodObject->getFilterObject($current10,$_POST['filter'],$this->lang);
if(!empty($AccommodObject)){
$AccommodObjectIds3[]=$AccommodObject['AccommodObject']['id'];
}
}
}else{
$AccommodObjectIds3=$AccommodObjectIds1;
}
//filtering by plyce
$AccommodObjectIds2=array();
if(!empty($_POST['filter']['place']))
{
$AccommodObjectDestinationArounds=$this->AccommodObjectDestinationAround->find('all',array('conditions' => array('AccommodObjectDestinationAround.destination_around_id' => $_POST['filter']['place']),'order' => array('AccommodObjectDestinationAround.accommod_object_id')));
foreach($AccommodObjectDestinationArounds as $current8){
$AccommodObjectIds2[]=$current8['AccommodObjectDestinationAround']['accommod_object_id'];
}
}
$AccommodObjectIdsFinale=array();
if(!empty($AccommodObjectIds2)){
foreach($AccommodObjectIds2 as $current9){
if(in_array($current9, $AccommodObjectIds3)) {
$AccommodObjectIdsFinale[]=$current9;
}
}
}else{
$AccommodObjectIdsFinale=$AccommodObjectIds3;
}
$arrival1=date('d.m.Y.',strtotime($search_period[0]));
$departure1=date('d.m.Y.',strtotime($search_period[count($search_period)-1]));
$arrival2=date('Y-m-d',strtotime($search_period[0]));
$departure2=date('Y-m-d',strtotime($search_period[count($search_period)-1]));
$AccommodUnitCounts=array();
$i=0;
foreach($AccommodUnits as $current2){
if(in_array($current2['AccommodUnit']['accommod_object_id'], $AccommodObjectIdsFinale)) {
$AccommodUnitCounts[$i]=$current2;
$AccommodUnitCounts[$i]['AccommodUnit']['arrival']=$arrival1;
$AccommodUnitCounts[$i]['AccommodUnit']['departure']=$departure1;
}
$i++;
}
$this->set('destination_main_id', $destination_main_id);
$this->set('accommod_main_id', $accommod_main_id);
$this->set('search_period_code', $search_period_code);
$this->set('total_person', $total_person);
$this->set('order',$order);
$this->set('range_days',$range_days);
$this->set('arrival',$arrival1);
$this->set('departure',$departure1);
//danas i tekuća godina
$today=date("Y-m-d");
$year=date("Y");
///////////////definition of free units (booking)
$SearchUnits=array();
$SearchUnitsIDs=array();
if(!empty($AccommodUnitCounts)){
$i=0;
foreach($AccommodUnitCounts as $current3){
//booking
$this->AccommodUnitBooking->locale = $this->lang;
$this->AccommodUnitBooking->recursive = -1;
$AccommodUnitBooking=$this->AccommodUnitBooking->find('first',array('conditions' => array('AccommodUnitBooking.accommod_unit_id' => $current3['AccommodUnit']['id'])));
if(!empty($AccommodUnitBooking)){
$this->AccommodUnitTablebooking->locale = $this->lang;
$this->AccommodUnitTablebooking->recursive = -1;
$AccommodUnitTablebookings=$this->AccommodUnitTablebooking->find('all',array('conditions' => array('AccommodUnitTablebooking.accommod_unit_id' => $current3['AccommodUnit']['id'], 'AccommodUnitTablebooking.accommod_unit_booking_id' => $AccommodUnitBooking['AccommodUnitBooking']['id'],'AccommodUnitTablebooking.booking' => $search_period ),'order' => array('AccommodUnitTablebooking.booking' => 'asc')));
if(!empty($AccommodUnitTablebookings)){
unset($current3);
}else{
$SearchUnits[]=$current3;
$SearchUnitsIDs[]=$current3['AccommodUnit']['id'];
}
}else{
$SearchUnits[]=$current3;
$SearchUnitsIDs[]=$current3['AccommodUnit']['id'];
}
$i++;
}
}
///////////////price calculation
if(!empty($SearchUnits)){
$i=0;
foreach($SearchUnits as $current6){
$booking_interval=count($this->Calendar->getDatesBetweenDates($arrival2, $departure2))-1;
$booking_interval_dates=array_slice($this->Calendar->getDatesBetweenDates($arrival2, $departure2),0,-1);
$accommod_booking=0;
if(!empty($current6['AccommodUnit']['fl_minute_start']) AND !empty($current6['AccommodUnit']['fl_minute_end']) AND !empty($current6['AccommodUnit']['fl_minute_price']) AND $current6['AccommodUnit']['fl_minute_start']==$arrival2 AND $current6['AccommodUnit']['fl_minute_end']==$departure2 ){ //LAST/FIRST MINUTE CIJENA
$accommod_booking=$current6['AccommodUnit']['fl_minute_price'];
$total=$accommod_booking*$booking_interval;
}else{
$this->AccommodUnitPrice->locale = $this->lang;
$this->AccommodUnitPrice->recursive = -1;
$AccommodUnitPrice=$this->AccommodUnitPrice->find('first',array('conditions' => array('AccommodUnitPrice.accommod_unit_id' => $current6['AccommodUnit']['id'])));
$period=array();
$total=0;
foreach($booking_interval_dates as $interval_date){
for($j=1; $j<=7; $j++){
if(!empty($AccommodUnitPrice['AccommodUnitPrice']['period'.$j])){
$period[$j]=$AccommodUnitPrice['AccommodUnitPrice']['period'.$j];
$date[$j]=split('[/.-]', $period[$j]);
$date_start[$j]=$year.'-'.$date[$j][1].'-'.$date[$j][0];
$date_end[$j]=$year.'-'.$date[$j][4].'-'.$date[$j][3];
if($date_start[$j]<=$interval_date AND $date_end[$j]>=$interval_date){//ako interval rezervacije pada u razdoblje cjenika
$this->AccommodUnitTableprice->locale = $this->lang;
$this->AccommodUnitTableprice->recursive = -1;
$AccommodUnitTableprice=$this->AccommodUnitTableprice->find('first',array('conditions' => array('AccommodUnitTableprice.accommod_unit_id' => $current6['AccommodUnit']['id'],'AccommodUnitTableprice.accommod_unit_price_id' => $AccommodUnitPrice['AccommodUnitPrice']['id'],'AccommodUnitTableprice.person_no' => $total_person,'AccommodUnitTableprice.day_no <=' => $booking_interval),'order' => array('AccommodUnitTableprice.person_no' => 'asc') ));
if(empty($AccommodUnitTableprice)){
$AccommodUnitTableprice=$this->AccommodUnitTableprice->find('first',array('conditions' => array('AccommodUnitTableprice.accommod_unit_id' => $current6['AccommodUnit']['id'],'AccommodUnitTableprice.accommod_unit_price_id' => $AccommodUnitPrice['AccommodUnitPrice']['id'],'AccommodUnitTableprice.day_no <=' => $booking_interval),'order' => array('AccommodUnitTableprice.person_no' => 'asc') ));
}
if(!empty($AccommodUnitTableprice)){
$accommod_booking=$AccommodUnitTableprice['AccommodUnitTableprice']['price'.$j];
$total=$total+$accommod_booking;
}
}
}
}
}
}
//destination
$this->DestinationMain->locale = $this->lang;
$this->DestinationMain->recursive = -1;
$DestinationMain=$this->DestinationMain->find('first',array('conditions' => array('DestinationMain.id' => $current6['AccommodUnit']['destination_main_id'],'DestinationMain.active' => '1')));
$SearchUnits[$i]['DestinationMain']=$DestinationMain['DestinationMain'];
//accommodation object
$this->AccommodObject->locale = $this->lang;
$this->AccommodObject->recursive = -1;
$AccommodObject=$this->AccommodObject->find('first',array('conditions' => array('AccommodObject.id' => $current6['AccommodUnit']['accommod_object_id'],'AccommodObject.active' => '1')));
$SearchUnits[$i]['AccommodObject']=$AccommodObject['AccommodObject'];
//url-ovi kod tražilice za smještajnu jedinicu
$SearchUnits[$i]['AccommodUnit']['arrival_url']=date('Y-m-d',strtotime($current6['AccommodUnit']['arrival']));
$SearchUnits[$i]['AccommodUnit']['departure_url']=date('Y-m-d',strtotime($current6['AccommodUnit']['departure']));
//kalkulacija
if(!empty($AccommodObject['AccommodObject']['info_cleaning']) AND !empty($AccommodObject['AccommodObject']['supplement_cleaning'])){
$SearchUnits[$i]['AccommodUnit']['total_price']=$total+$AccommodObject['AccommodObject']['supplement_cleaning'];
}else{
$SearchUnits[$i]['AccommodUnit']['total_price']=$total;
}
$i++;
}
}
////filtriranje po cijeni
$max_value=800; //max price
if(!empty($_POST['filter']['price1']) OR (!empty($_POST['filter']['price2']) AND !empty($_POST['filter']['price2'])!=$max_value)){
$i=0;
$FilterPriceUnits=array();
foreach($SearchUnits as $current11){
if($current11['AccommodUnit']['total_price']>$_POST['filter']['price1'] AND $current11['AccommodUnit']['total_price']<=$_POST['filter']['price2'] ){
$FilterPriceUnits[]=$current11;
}
$i++;
}
$SearchUnits=array();
$SearchUnits=$FilterPriceUnits;
}
//pageing
$limit=15;
if($pageNum=='' OR !is_numeric($pageNum)){
$pageNum=1;
}
$nOfItems=count($SearchUnits);
$pages=$this->Pagination->makePagination($nOfItems, $pageNum, $limit,2, 2, '...');
$this->set('pages',$pages);
$this->set('pageNum',$pageNum);
$SearchUnitFinales = Set::sort($SearchUnits, '{n}.AccommodUnit.total_price', $order);
$offset=($pageNum-1)*$limit;
$SearchUnitSlices = array_slice($SearchUnitFinales, $offset, $limit);
$this->set('accommod_unit_slices', $SearchUnitSlices);
}
Since your tag says php I would suggest looking into memcached. Also you would need to have pagination and load data only on page change, here is an example:
//user clicked page number, 1,2,3 etc...
$currentPage = isset($_POST['page']) ? (int)$_POST['page'] : 1;
// get 25 rows per page
$startLimit = ($currentPage-1) * 25;
$endLimit = $startLimit + 25;
then you can use these limits in your query to grab only 25 records per page. Also I would use cache so everytime you change page does not have to execute query.
Related
I am trying to import data into MySQL from a JSON file.
public function importProductFile($file, $return = true)
{
$products = json_decode($file);
$dubTableName = Product::tableName() . "_dub";
$start = time();
if ($this->db->createDuplicateTable(Product::tableName(), $dubTableName)) {
$i = 0;
foreach ($products as $product) {
$i++;
$item = new Product_dub();
$item->id_1c_product = $product->id;
$category = Category_dub::findOne(['id_1c_category' => $product->category_id]);
if (!$category) {
Answer::failure("В этом товаре отсутствует категория или такой категории не существует: " . $product->title);
}
$item->category_id = $category->id;
$item->title = $product->title;
$brand = Brands_dub::findOne(['id_1c_brand' => $product->brand_id]);
if (!$brand) {
Answer::failure("В этом товаре отсутствует бренд/изготовитель: " . $product->title);
}
$item->brand_id = $brand->id;
// $item->shortdesc = $product->shortdesc;
$item->content1 = $product->content1;
$item->content2 = $product->content2;
$item->content3 = $product->content3;
$item->link_order = $product->link_order;
$item->img = $product->img;
$item->in_stock = $product->in_stock ? 1 : 0;
$item->is_popular = $product->is_popular ? 1 : 0;
if (!$item->save()) {
Answer::failure("Не удалось импортировать: Проверьте данные в " . $product->title);
}
if ($i == 200) {
break;
}
}
}
$finish = time();
$res = $finish - $start . "sec. ";
if ($return) {
echo $res;
Answer::success();
}
}
There are about 1100 objects in my JSON file. It takes 7 seconds to add 100 rows to the database. Adding 200 lines - 15 seconds. 300 = 33 sec, 400 = 58 sec. Why does it slow down over time and how to speed up this process?
I do everything on the local OpenServer server.
PHP 7.2 version, Xeon 2620v3 processor, 16 GB DDR4, HDD.
UPD 1.
"Can you try not importing and just determine the speed of reading" - I comment $item->save() and get 1-2 sec for all of JSON files. "In each iteration of your cycle you are running 2 DB queries to load category and brand." - I tried to delete these lines for test - but the result was 1-2 seconds faster than with 2 DB queries.
UPD 2.
I changed save() to insert() - the speed has increased. Now all JSON (1107 lines) is imported in 40 seconds.
Are there faster ways to load ready-made data from JSON into the database?
What if there are 100 thousand lines or a million? Is it normal practice to wait a few hours?
public function importProductFile($file, $return = true)
{
$products = json_decode($file);
$dubTableName = Product::tableName() . "_dub";
$start = time();
if ($this->db->createDuplicateTable(Product::tableName(), $dubTableName)) {
$start = time();
$categoryMap = Category_dub::find()->select(['id', 'id_1c_category'])->indexBy('id_1c_category')->column();
$brandMap = Brands_dub::find()->select(['id', 'id_1c_brand'])->indexBy('id_1c_brand')->column();
foreach ($products as $product) {
Yii::$app->db->createCommand()->insert('product_dub', [
'id_1c_product' => $product->id,
'category_id' => $categoryMap[$product->category_id] ?? '0',
'title' => $product->title,
'brand_id' => $brandMap[$product->brand_id] ?? 'No brand',
'content1' => $product->content1,
'content2' => $product->content2,
'content3' => $product->content3,
'link_order' => $product->link_order,
'img' => $product->img ?? 'no-image.png',
'in_stock' => $product->in_stock ? 1 : 0,
'is_popular' => $product->is_popular ? 1 : 0,
])->execute();
}
}
}
$finish = time();
$res = $finish - $start . "sec. ";
if ($return) {
echo $res;
Answer::success();
}
}
I changed save() to insert() - the speed has increased. Now all JSON (1107 lines) is imported in 40 seconds.
Are there faster ways to load ready-made data from JSON into the database?
What if there are 100 thousand lines or a million? Is it normal practice to wait a few hours?
public function importProductFile($file, $return = true)
{
$products = json_decode($file);
$dubTableName = Product::tableName() . "_dub";
$start = time();
if ($this->db->createDuplicateTable(Product::tableName(), $dubTableName)) {
$start = time();
$categoryMap = Category_dub::find()->select(['id', 'id_1c_category'])->indexBy('id_1c_category')->column();
$brandMap = Brands_dub::find()->select(['id', 'id_1c_brand'])->indexBy('id_1c_brand')->column();
foreach ($products as $product) {
Yii::$app->db->createCommand()->insert('product_dub', [
'id_1c_product' => $product->id,
'category_id' => $categoryMap[$product->category_id] ?? '0',
'title' => $product->title,
'brand_id' => $brandMap[$product->brand_id] ?? 'No brand',
'content1' => $product->content1,
'content2' => $product->content2,
'content3' => $product->content3,
'link_order' => $product->link_order,
'img' => $product->img ?? 'no-image.png',
'in_stock' => $product->in_stock ? 1 : 0,
'is_popular' => $product->is_popular ? 1 : 0,
])->execute();
}
}
}
$finish = time();
$res = $finish - $start . "sec. ";
if ($return) {
echo $res;
Answer::success();
}
}
You can use the bulk insert as mentioned in this answer and Yii2 docs. Using this bulk insert, you need to remember that the event will not be triggered.
Yii::$app->db->createCommand()->batchInsert('product_dub', array_keys(reset($products)), $products)->execute();
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'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 need to get the average number of a grade in a function. Doesn't seem to work completly.. Thanks for your help.
This is what I have so far:
<?php
function povprecje($d,$t){
$v=0;
foreach($t as $x=>$y){
foreach($y as $d=>$grade){
$v = $v+$grade;
$v = $v/count($grade);
return $v;
}
}
}
$t = array(
"Student" => array(
"math" => 3,
"algebra" => 4,
"science" => 4
)
);
echo povprecje("math",$t);
?>
Maybe You wanted to achieve this?
function povprecje($sSubject, $aGrades) {
$iGradesSum = 0;
$iAmount = 0;
foreach($aGrades as $aStudentGrades) {
if(isset($aStudentGrades[$sSubject])) {
$iGradesSum+= $aStudentGrades[$sSubject];
$iAmount++;
}
}
return $iGradesSum / $iAmount;
}
Function call:
echo povprecje("math", $t);
I'm working with a couple of arrays, one of which has keys that are the productid, the value being an object that contains a doctrine entity of that product. Similarly, I have a plan with the index being the plan Id. For this for loop, I need to go through and individually set up invoices for each plan-product pair (the quantity will always be the same between them, except in cases where a user is purchasing a plan for an already owned device). Obviously this is somewhat complicated, so I'm not exactly sure how to phrase this question. An error occurs at the commented line, "Notice: Undefined Index"
for ($i = 0; $i < $totalInvoices; $i++) {
if ($i == $planQuantity[key($plans)]) {
next($plans);
}
if ($i == $productQuantity[key($products)]) {
next($products);
}
$data = array(
'planId' => key($plans),
//below here, I'm thinking at key($products) is where the error occurs
'productId' => key($products) != 0 ? key($products) : $plans[key($plans)]->getPricingTier()->getProductId(),
'userId' => $this->userId,
'paymentMethodId' => $paymentMethodId
);
if ($order['hasProduct'] || isset($order['activating'])) {
if (!isset($order['activating'])) {
$planModel->createDevicePlan($data);
$productAmount = $products[key($products)]->getAmount();
} else {
$data['deviceId'] = $order['activating']['inventoryId'];
$planModel->createDevicePlan($data, date('Y-m-d'));
$productAmount = 0;
}
} else {
$productAmount = 0;
}
if ($iteration % 5 == 0 && $order['hasShipping']) {
$invoiceShippingAmount = $billingModel->getShippingAmount($shippingOptionsId);
} else {
$invoiceShippingAmount = 0;
}
$salesData = array(
'paymentMethodsId' => $paymentMethodId,
'planAmount' => $plans[key($plans)]->getAmount(),
'planId' => key($plans),
'productAmount' => $productAmount,
'productId' => key($products),
'shippingAddressesId' => $shippingAddressId,
'shippingAmount' => $invoiceShippingAmount,
'shippingOptionsId' => $shippingOptionsId,
'transactionId' => $transactionId,
'userId' => $this->userId
);
$iteration++;
$billingModel->createInvoice($salesData);
}
Any help would be greatly appreciated.
Based on your comment reply, I think this will help
$plans_on_invoice = 0;
$products_on_invoice = 0;
for ($i = 0; $i < $totalInvoices; $i++) {
next($plans);
if ($plans_on_invoice == 0) {
$plans_on_invoice = $planQuantity[key($plans)];
}
plans_on_invoice--;
next($products);
if ($products_on_invoice == 0) {
$products_on_invoice = $productQuantity[key($products)];
}
products_on_invoice--;