Php ile Ayın Tüm Hafta İçi Günlerini Bulma
Merhaba arkadaşlar. Bugün, bulunduğumuz hafta da dahil olmak üzere, ayın tüm hafta içi günlerini bulmam gerekiyordu. İstediğiniz gibi yazdığınız kodları kullanarak istediğiniz günleri elde edebilirsiniz. Çok basit. Sadece DateTime sınıfını bilmeniz yeterli.
Bir dizide yalnızca hafta içi günlerini topluyorum. Hafta sonlarını dahil etmiyorum. Bu $lastDay değişkenini Cuma olarak ayarladıktan sonra, her döngünün başında $lastDay değişkenini 3 gün sonrasına güncelliyorum. Böylece pazartesiyi buluyor ve her günü ayrı ayrı diziye ekliyorum.
<?php // Set Today $today = new DateTime(); // Find beginning of the week $monday = clone $today; $monday = $monday->modify(('Sunday' == $monday->format('l')) ? 'Monday last week' : 'Monday this week'); // I will set the variable $lastDay in the loop to the previous week's date. So I can update it on a Monday. $lastDay = clone $monday; $lastDay = $lastDay ->modify('-3 day'); // We create an array that specifies 5 weeks. $dates = array( "week1" => array(), "week2" => array(), "week3" => array(), "week4" => array(), "week5" => array() ); // We are starting loop. Here we put our $dates array into foreach. foreach ($dates as $key => $date) { // We use the $lastDay variable to find the first day of the week. $firstDay = clone $lastDay; $firstDay = $firstDay->modify('+3 day'); // After that, we increase the days to finding the remaining 4 days. $secondDay = clone $firstDay; $secondDay = $secondDay->modify('+1 day'); $thirdDay = clone $secondDay; $thirdDay = $thirdDay->modify('+1 day'); $forthDay = clone $thirdDay; $forthDay = $forthDay->modify('+1 day'); $fifthDay = clone $forthDay; $fifthDay = $fifthDay->modify('+1 day'); // We set the $lastDay variable to the 5th day, ie Friday. In this way, we will be able to find Monday at beginning of the loop. $lastDay = clone $fifthDay; // I am adding dates to the corresponding week in the $date array. I used different indexes here. You can edit it as you like. $dates[$key] = array( $firstDay->format('M d D') => $firstDay->format('Y-m-d'), $secondDay->format('M d D') => $secondDay->format('Y-m-d'), $thirdDay->format('M d D') => $thirdDay->format('Y-m-d'), $forthDay->format('M d D') => $forthDay->format('Y-m-d'), $fifthDay->format('M d D') => $fifthDay->format('Y-m-d'), ); }