So, I have created a script in PHP that sets a greeting dependent on date and time. The code checks for any seasonal events, and if there are none, it checks the time and assigns the appropriate greeting. My issue that I am having is:
I have set the value to check if the time is past 18:00, if it is past this time, it should set an evening greeting. My issue is that if I change the php if argument value to a time in the future, it still keeps the greeting as an evening greeting. What could be wrong?
Here is my code:
$morningGreetings = array(
1 => "Good morning",
2 => "Morning",
);
$standardGreetings = array(
1 => "Hello",
2 => "Howdy",
3 => "Hiya",
4 => "Greetings",
5 => "Great to see you",
6 => "Hi there",
7 => "Hi",
8 => "Good day",
);
$eveningGreetings = array(
1 => "Evening",
2 => "Good evening",
);
$seasonalGreetings = array(
1 => "Merry Christmas",
2 => "Happy New Year",
);
$eventGreetings = array(
1 => "Happy Birthday",
);
if (date("d m") != strtotime("25 12")) {
if (date("d m") != strtotime("0 0")) {
if (date("G i") <= strtotime("18 00")) {
if (date("G i") <= strtotime("09 00")) {
$sizeOfArray = sizeof($standardGreetings);
$greetingValue = rand(1, $sizeOfArray);
$greeting = $standardGreetings[$greetingValue];
} else {
$sizeOfArray = sizeof($morningGreetings);
$greetingValue = rand(1, $sizeOfArray);
$greeting = $morningGreetings[$greetingValue];
}
} else {
$sizeOfArray = sizeof($eveningGreetings);
$greetingValue = rand(1, $sizeOfArray);
$greeting = $eveningGreetings[$greetingValue];
}
} else {
$greeting = $seasonalGreetings[2];
}
} else {
$greeting = $seasonalGreetings[1];
}
Maybe something like this:
EDIT
$seasonalGreetingA=array();
$seasonalGreetingA[]=array('dayBegin'=>30,'monthBegin'=>12,'dayEnd'=>31,'monthEnd'=>12,'text'=>'Happy New Year');
$seasonalGreetingA[]=array('dayBegin'=>1,'monthBegin'=>1,'dayEnd'=>2,'monthEnd'=>1,'text'=>'Happy New Year');
$seasonalGreetingA[]=array('dayBegin'=>21,'monthBegin'=>6,'dayEnd'=>23,'monthEnd'=>9,'text'=>'Happy Spring');
$seasonalGreetingA[]=array('dayBegin'=>12,'monthBegin'=>11,'dayEnd'=>23,'monthEnd'=>11,'text'=>'Happy All');
$dateGreetingA=array();
$dateGreetingA[]=array('date'=>'2014-11-09','text'=>'Happy Birthday');
$timeGreetingA=array();
$timeGreetingA[]=array('timeBegin'=>8,'timeEnd'=>12,'text'=>'Morning');
$timeGreetingA[]=array('timeBegin'=>8,'timeEnd'=>12,'text'=>'Good morning');
$timeGreetingA[]=array('timeBegin'=>18,'timeEnd'=>23,'text'=>'Evening');
$timeGreetingA[]=array('timeBegin'=>18,'timeEnd'=>23,'text'=>'Good evening');
$timeGreetingA[]=array('timeBegin'=>23,'timeEnd'=>24,'text'=>'Time out');
$timeGreetingA[]=array('timeBegin'=>13,'timeEnd'=>18,'text'=>'Good afternoon');
$standardGreetingA[]=array();
$standardGreetingA[]=array('text'=>'Hello');
$standardGreetingA[]=array('text'=>'Howdy');
$standardGreetingA[]=array('text'=>'Hi');
$txtGreeting='';
$date=date('Y-m-d');
if($txtGreeting=='')
if(count($dateGreetingA)>0)
foreach($dateGreetingA as $dgA)
{
if($dgA['date']==$date)
{
$txtGreeting=$dgA['text'];
break;
}
}
$d=(int)date('d');
$m=(int)date('m');
if($txtGreeting=='')
if(count($seasonalGreetingA)>0)
foreach($seasonalGreetingA as $sgA)
{
$d1=$sgA['dayBegin'];
$m1=$sgA['monthBegin'];
$d2=$sgA['dayEnd'];
$m2=$sgA['monthEnd'];
//echo $m1.' >= '.$m.' <= '.$m2.'<br />';
if($m>=$m1 and $m<=$m2)
if($d>=$d1 and $d<=$d2)
$txtGreeting=$sgA['text'];
}
$time=(int)date('H');
if($txtGreeting=='')
if(count($timeGreetingA)>0)
foreach($timeGreetingA as $tgA)
{
if($time>=$tgA['timeBegin'] and $time<= $tgA['timeEnd'])
{
$txtGreeting=$tgA['text'];
break;
}
}
if($txtGreeting=='')
if(count($standardGreetingA)>0)
{
$ind=rand(0,count($standardGreetingA)-1);
if(isset($standardGreetingA[$ind])) $txtGreeting=$standardGreetingA[$ind]['text'];
}
echo $txtGreeting;
exit;
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();
i need to check whether the current time lies between the range
these r restaurant open timings ,timings can be like open now till next morning or closed for sometime same day and open next half same day till next day or midnight
examples
Case1: 10:00 01:00
Case2: 10:00 23:59
Case3: 10:00 00:00
Case4: 23:59 05:00
Case5: 08:35 15:30 && 17:30 02:00
Case6: 10:00 15:00 && 17:00 00:00
all the cases must be checked
if((strtotime($s)<=strtotime($myTime)) && (strtotime($e)>=strtotime($myTime)))
{$open =1;}
if($e=="00:00")
{ if((strtotime($s)<=strtotime($myTime))&& (strtotime($myTime)>=strtotime("00:00")))
{$open =1;}}
this is not working where m i going wrong
Something like this might work. I've not really tested it.
$currentTime = time();
function in_range($what, $min, $max) {
return $what >= $min && $what <= $max;
}
var_dump(in_range($currentTime, strtotime('08:35'), strtotime('15:30'));
// etc.
Use DateTime objects for comparison like this. See http://php.net/manual/en/class.datetime.php
$cases = array(
array(
'start' => new DateTime("10:00:00"),
'end' => new DateTime("12:00:00"),
),
array(
'start' => new DateTime("10:00:00"),
'end' => new DateTime("23:59:00"),
),
array(
'start' => new DateTime("10:00:00"),
'end' => new DateTime("00:00:00"),
),
array(
'start' => new DateTime("23:59:00"),
'end' => new DateTime("05:00:00"),
),
);
//adjust dates
$cases[2]['end']->modify('+1 day');
$cases[3]['start']->modify('-1 day');
$now = new DateTime();
foreach ($cases as $key => $value) {
if ($now > $value['start'] && $now < $value['end']) {
echo 'case ' . $key . ' ok' . PHP_EOL;
}
else {
echo 'case ' . $key . ' out of range' . PHP_EOL;
}
}
Right-o, had a mess around for you. Do you want to see if this is getting your expected output? Seems to be working on my local tests. Fair bit of code mind, turned out to be a few edge cases to consider.
Potentially bits of it that can be refactored and improved, but i'll leave that up to you if it works as intended.
<?php
$cases = [
[['start' => '09:00', 'end' => '01:00']],
[['start' => '10:00', 'end' => '23:59']],
[['start' => '10:00', 'end' => '00:00']],
[['start' => '23:59', 'end' => '05:00']],
[['start' => '10:00', 'end' => '15:00'], ['start' => '17:30', 'end' => '02:00']],
[['start' => '10:00', 'end' => '15:00'], ['start' => '17:30', 'end' => '00:00']],
];
$cases = setUpCases($cases);
foreach ($cases as $case) {
$withinTimeRange = isTimeWithinCase((new DateTime()), $case);
if ($withinTimeRange) {
break;
}
}
// Boolean True/False whether it is within any of the ranges or not.
// i.e. True = Shop Open, False = Shop closed.
var_dump($withinTimeRange);
function setUpCases($cases) {
return array_map(function($case) {
return convertToDateTimeObjects($case);
}, $cases);
}
function convertToDateTimeObjects($case) {
$formatted = [];
foreach ($case as $index => $times) {
$s = new DateTime();
list($hour, $minute) = explode(':', $times['start']);
$s->setTime($hour, $minute, 00);
$e = new DateTime();
list($hour, $minute) = explode(':', $times['end']);
$e->setTime($hour, $minute, 00);
if ($e < $s) $e->modify('+1 day');
$formatted[] = ['start' => $s, 'end' => $e];
}
return $formatted;
}
function isTimeWithinCase($time, $case) {
foreach ($case as $timerange) {
return ($time > $timerange['start'] && $time < $timerange['end']);
}
}
I have been thinking about this task carefully. And i came up with the logic that is required to calculate whether the current time is in between 2 times. There are the following two cases to calculate that:
Case 1: The starting time is greater than the ending time
Which means the ending time must be the next day. That means that if your current time is less than the ending time OR greater than the start time, your time is in between the two times.
Case 2: The starting time is less than the ending time
In this case, the start time and the ending time is the same day. For this, the logic that is needed is to check whether or not your time is greater than the start time AND less than the ending time. If that's statement is true, your time is in between the two times.
I have made the following function for calculating that:
function checktime($arr,$time) {
list($h,$m)=explode(":",$time);
if(!is_array($arr[0])) {
$r1=explode(":",$arr[0]);
$r2=explode(":",$arr[1]);
if($r1[0]>$r2[0]) {
if(($h>$r1[0] || ($h==$r1[0] && $m>=$r1[1])) || ($h<$r2[0] || ($h==$r2[0] && $m<=$r2[1]))) return true;
}
else {
if(($h>$r1[0] || ($h==$r1[0] && $m>=$r1[1])) && ($h<$r2[0] || ($h==$r2[0] && $m<=$r2[1]))) return true;
}
}
}
And here are some tests, for testing the limits of the cases you gave me:
$arr=array("10:00","01:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//True
$arr=array("10:00","23:59");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//False
$arr=array("10:00","00:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//True
$arr=array("23:59","05:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//False
echo (checktime($arr,"00:00")?"True":"False");//True
$arr=array("08:35","15:30");
echo (checktime($arr,"23:59")?"True":"False");//False
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//False
$arr=array("17:30","02:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//False
echo (checktime($arr,"00:00")?"True":"False");//True
$arr=array("10:00","15:00");
echo (checktime($arr,"23:59")?"True":"False");//False
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//False
$arr=array("17:00","00:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//False
echo (checktime($arr,"00:00")?"True":"False");//True
this works for all the casese
$let=array("01:00","02:00","03:00","05:00","04:00");
if((strtotime($s)<=strtotime($myTime)) && (!strcmp($e,"00:00")))
{ $open=1;$flag=1;}
if((strtotime($s)<=strtotime($myTime)) && (!strcmp($e,"23:59")))
{ $open=1;$flag=1;}
if(in_array($e,$let))
{
if(strtotime($s)<=strtotime($myTime))
{ $open=1;$flag=1;}
else
if(strtotime($e)>=strtotime($myTime))
{ $open=1;$flag=1;}
}
if(!$flag)
{if((strtotime($s)<=strtotime($myTime)) && (strtotime($e)>=strtotime($myTime)))
{ $open=1;} }
I'm quite frustrated with the following code, which should show the Zodiac sign of a baby by using only date and month.
$babyDue= date('d-m',strtotime("23-04-2015"));
$ariesStart=date('d-m',strtotime("21-03-2016"));
$ariesEnd=date('d-m',strtotime("20-04-2016"));
$taurusStart=date('d-m',strtotime("21-04-2016"));
$taurusEnd=date('d-m',strtotime("20-05-2016"));
$zodiac="thisTextNeedToChange";
if(($babyDue>$ariesStart) && ($babyDue<$ariesEnd)) {
//Set $zodiac to aries
$zodiac="aries";
echo $zodiac;
} elseif (($babyDue>$taurusStart)&& ($babyDue<$taurusEnd)){
//Set $zodiac to Taurus
$zodiac="Taurus";
echo $zodiac;
}
I think my logic is correct, but it's not showing anything :(
$babyBirthDate = new DateTime('23 April');
$zodiacs = array(
'Aries' => array(
new DateTime('21 March'),
new DateTime('20 April'),
),
'Taurus' => array(
new DateTime('21 April'),
new DateTime('20 May'),
)
);
foreach ($zodiacs as $zodiac => $dateTimeRange) {
if ($babyBirthDate >= $dateTimeRange[0] && $babyBirthDate <= $dateTimeRange[1]) {
echo $zodiac;
break;
}
}
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.
I faced an interview question which i felt was very good. Couldn't achieve the complete answer, however, felt sharing and asking the right method to code it in PHP.
The question goes as :
Given the Japanese numeral reading system, write a program that converts an integer into the equivalent Japanese reading.
Basic numeral readings:
1: ichi
2: ni
3: san
4: yon
5: go
6: roku
7: nana
8: hachi
9: kyuu
10: juu
20: ni-juu
30: san-juu
100: hyaku
1000 : sen
10,000: man
100,000,000: oku
1,000,000,000,000: chou
10,000,000,000,000,000: kei
Exceptions due to voice rounding in Japanese reading:
300: sanbyaku
600: roppyaku
800: happyaku
3000: sanzen
8000: hassen
1,000,000,000,000: itchou
8,000,000,000,000: hatchou
10,000,000,000,000: jutchou (also applies to multiplies of 10,000,000,000,000)
10,000,000,000,000,000: ikkei
60,000,000,000,000,000: rokkei
80,000,000,000,000,000: hakkei
100,000,000,000,000,000: jukkei (also applies to multiplies of 10,000,000,000,000,000)
1,000,000,000,000,000,000: hyakkei (also applies to multiplies of 1,000,000,000,000,000,000)
Starting at 10,000, numbers begin with ichi if no digit would otherwise precede, e.g. 1,000 is sen but 10,000 is ichi-man.
Examples:
11: juu ichi
17: juu nana
151: hyaku go-juu ichi
302: san-byaku ni
469: yon-hyaku roku-juu kyuu
2025 : ni-sen ni-juu go
10,403: ichi-man yon-byaku san
41,892: yon-juu ichi-man happyaku kyuu-juu ni
80,000,000,000,000: hachi-jutchou
The code that i have tried is :
$inputNumber = 2025;
$inputString = (String)$inputNumber;
$numeralReadings = array(
1 => 'ichi',
2 => 'ni',
3 => 'san',
4 => 'yon',
5 => 'go',
6 => 'roku',
7 => 'nana',
8 => 'hachi',
9 => 'kyuu',
10 => 'juu',
20 => 'ni-juu',
30 => 'san-juu',
100 => 'hyaku',
1000 => 'sen',
10000 => 'man',
100000000 => 'oku',
1000000000000 => 'chou',
10000000000000000 => 'kei'
);
$numeralExceptions = array(
300 => 'sanbyaku',
600 => 'roppyaku',
800 => 'happyaku',
3000 => 'sanzen',
8000 => 'hassen',
1000000000000 => 'itchou',
8000000000000 => 'hatchou',
10000000000000 => 'jutchou',
10000000000000000 => 'ikkei',
60000000000000000 => 'rokkei',
80000000000000000 => 'hakkei',
100000000000000000 => 'jukkei',
1000000000000000000 => 'hyakkei'
);
if ($inputString > 10000) {
$inp1 = floor($inputString / 1000);
$inp = $inputString - ($inp1 * 1000);
if($inp !== 0) {
read($inp1, $numeralReadings, $numeralExceptions, false);
read($inp, $numeralReadings, $numeralExceptions);
} else {
read($inputString, $numeralReadings, $numeralExceptions);
}
} else {
read($inputString, $numeralReadings, $numeralExceptions);
}
function read($inputStr, $numeralReadings, $numeralExceptions, $parse1 = true)
{
$splitString = str_split($inputStr);
$returnString = '';
$appendIchi = false;
$firstNumber = null;
foreach ($splitString as $key => $number) {
if ($firstNumber == null) {
$firstNumber = $number;
}
if ($number !== 0) {
$int = 1;
$a = count($splitString) - 1 - $key;
for ($i = 0; $i < $a; $i++) {
$int = $int * 10;
}
$tempNumber = (int)$number * $int;
if (isset($numeralExceptions[$tempNumber])) {
$returnString .= $numeralExceptions[$tempNumber] . ' ';
continue;
}
if (isset($numeralReadings[$tempNumber])) {
if ($parse1 == false && $tempNumber == 1) {
continue;
}
$returnString .= $numeralReadings[$tempNumber] . ' ';
continue;
}
if (isset($numeralReadings[(int)$number])) {
if ($parse1 == false && $tempNumber == 1) {
continue;
}
$returnString .= $numeralReadings[(int)$number];
if ($int !== 1) {
$returnString .= '-' . $numeralReadings[$int];
}
$returnString .= ' ';
}
}
}
echo $returnString;
}
here is a fiddle that shows the code in running. You might want to try it online. Link
With the code above, i was able to achieve all the examples stated above other than the last 2.
Anyone who can solve this in a better way?
I guess you can simply use array_key_exists() here
function read($inputStr, $numeralReadings, $numeralExceptions)
{
if(array_key_exists($inputStr, $numeralReadings))
{
return $numeralReadings[$inputStr];
}
else if(array_key_exists($inputStr, $numeralExceptions))
{
return $numeralExceptions[$inputStr];
}
else
{
return "not found";
}
}