Ajax mouseover show function alignment - php

I am trying to open a box by using mouseover function, however the box always shows on the right part of the object. Hence when the object is right end of the page, the whole box cannot be seen as shown in this photo.
https://rapidshare.com/files/998669066/problem.png
Here is my ajax code:
$(document).ready(function() {
$('.date-available').click(function() {
alert($(this).attr('id'));
});
$('.rezerve-td').mouseover(function() {
$(this).children().show();
}).mouseout(function() {
$(this).children().hide();
});
});
What should i do in order prevent it? Thanks.
Here is the html part of my code:
require_once 'class.dates.php';
require_once 'class.generic.php';
require_once 'connection.php';
$query = mysql_query("SELECT * FROM egitim_salonu", $baglanti);
while ($row = mysql_fetch_object($query)) {
$salonlar[$row->id] = array('ad' => $row->ad, 'detay' => $row->detay);
}
$query = mysql_query("SELECT * FROM salon_rezervasyonu", $baglanti);
while ($row = mysql_fetch_object($query)) {
$rezervasyonlar[$row->salon_id.'%'.$row->gun.'%'.$row->tip] = array('salon_id' => $row->salon_id, 'gun' => $row->gun, 'tip' => $row->tip, 'rezerve_edildigi_egitim' => $row->rezerve_edildigi_egitim);
}
$month = date('m', strtotime($_POST['d']));
$year = date('Y', strtotime($_POST['d']));
$date = date('F Y', strtotime('01-'.$month.'-'.$year));
if ($month == 1 || $month == 3 || $month == 5 || $month == 7 || $month == 8 || $month == 10 || $month == 12) {
$numberOfDays = 31;
} else if ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
$numberOfDays = 30;
} else if (date('L', strtotime($year.'-01-01'))) {
$numberOfDays = 29;
} else {
$numberOfDays = 28;
}
// Tabloyu aç, başlığı hazırla
$output = '<table class="calendar" id="salon-rezervasyon-table">
<thead>
<tr><th rowspan="2">Salon</th><th colspan="'.(2 * $numberOfDays).'">'.$date.'</th></tr>
<tr>';
for ($i = 1; $i <= $numberOfDays; $i++) {
$output .= '<th width="10" colspan="2" class="day-th">'.$i.'</th>';
}
// Başlığı kapat, gövdeyi aç
$output .= '</tr></thead><tbody>';
// Her salon için...
foreach ($salonlar as $salonKey => $salonValue) {
$output .= '<tr id="salon-'.$salonKey.'"><td class="calendar-salon-column">'.$salonValue['ad'].'<br />'.$salonValue['detay'].'</td>';
// ... o ay içindeki günleri kontrol et. Burada kontrol için şunu yapıyoruz: salon id'si, tarih ve gün içerisindeki saati (öğleden önce, öğleden sonra)
// birleştirerek bir index (bu index unique bir index) oluşturuyoruz ve bu index yukarıdaki rezervasyonlar dizisinde tanımlanmış mı diye kontrol ediyoruz.
for ($i = 1; $i <= $numberOfDays; $i++) {
$dateCheck = date('Y-m-d', strtotime($i.'-'.$month.'-'.$year));
$rIndexOO = $salonKey.'%'.$dateCheck.'%Öğleden önce';
$rIndexOS = $salonKey.'%'.$dateCheck.'%Öğleden sonra';
//Öğleden önce
if(isset($rezervasyonlar[$rIndexOO])) {
$egitimPlaniQuery = mysql_query("SELECT * FROM egitim_plani WHERE id = ".$rezervasyonlar[$rIndexOO]['rezerve_edildigi_egitim'], $baglanti);
$egitimPlani = mysql_fetch_object($egitimPlaniQuery);
$output .= '<td id="'.$dateCheck.'%o" class="calendar-td rezerve-td">';
$output .= '<div class="rezerve">'.date('d-m-Y', strtotime($dateCheck)).' Öğleden Önce<br /><br />'.$egitimPlani->egitim_adi.'</div>';
$output .= '</td>';
} else {
$output .= '<td id="'.$dateCheck.'%o" class="date-available calendar-td">';
$output .= '';
$output .= '</td>';
}
//Öğleden sonra
if(isset($rezervasyonlar[$rIndexOS])) {
$egitimPlaniQuery = mysql_query("SELECT * FROM egitim_plani WHERE id = ".$rezervasyonlar[$rIndexOO]['rezerve_edildigi_egitim'], $baglanti);
$egitimPlani = mysql_fetch_object($egitimPlaniQuery);
$output .= '<td id="'.$dateCheck.'%s" class="calendar-td rezerve-td">';
$output .= '<div class="rezerve">'.date('d-m-Y', strtotime($dateCheck)).' Öğleden Sonra<br /><br />'.$egitimPlani->egitim_adi.'</div>';
$output .= '</td>';
} else {
$output .= '<td id="'.$dateCheck.'%o" class="date-available calendar-date-separator">';
$output .= '';
$output .= '</td>';
}
}
$output .= '</tr>';
}
$output .= '</tbody></table>';
echo $output;

You could probably fix this with some css.
div.rezerve {
position: absolute
}
If it still shows up off the page, you can add something like this to your javascript
....
var doc_width = $(document).width();
var rezerve_child = $(this).children();
rezerve_child.show();
var position = rezerve_child.offset();
var rezerve_child_width = rezerve_child.width();
if (position.left + rezerve_child_width > doc_width) {
$(this).css('right', '2px');
}
....
The jQuery Tooltip plugin would also probably be helpful.
http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/

Related

Having some diffculty parsing tree data in ul li format in php

i'm try to create trial balance i somehow achieve tree view in my array and now i want to print my code but don't know how to make tree because i don't know how many children i can get in future and i'm not very good at recursion below is my tree prepared array and i also attach my result that i can make via foreach loop but stuck in children node i can make children nodes via foreach but the problem is it's not a best approach to follow so please help me out to print my tree structure data as per my array. Any help would be appreciated.
Here my tree array look like : Tree Array
My result look like this this is only root nodes of an array and i using jstree to show hierarchy.
<?
$total_opening_debit = 0;
$total_opening_credit = 0;
$total_debit = 0;
$total_credit = 0;
foreach($this->trees as $key => $value)
{
foreach($value as $tree)
{
if($tree["id"] != "")
{
?>
<li>
<span class="first"><? echo $tree["name"]; ?></span>
<span class="other">
<?
if ($tree["opening_debit"] > $tree["opening_credit"])
{
echo format_currency($tree["opening_debit"] - $tree["opening_credit"], 2) . " Dr.";
}
elseif ($tree["opening_credit"] > $tree["opening_debit"])
{
echo format_currency($tree["opening_credit"] - $tree["opening_debit"], 2) . " Cr.";
}
else
{
echo "0";
}
$total_opening_debit += $tree["opening_debit"];
$total_opening_credit += $tree["opening_credit"];
?>
</span>
<span class="other">
<?
if($tree["period_debit"]<>"" && $tree["period_debit"]<>"0")
{
echo format_currency($tree["period_debit"], 2);
$total_debit += $tree["period_debit"];
}
else
{
echo 0;
}
?>
</span>
<span class="other">
<?
if($tree["period_credit"]<>"" && $tree["period_credit"]<>"0")
{
echo format_currency($tree["period_credit"], 2);
$total_credit += $tree["period_credit"];
}
else
{
echo 0;
}
?>
</span>
<span class="other">
<?
if ($tree["opening_debit"] + $tree["period_debit"] > $tree["opening_credit"] + $tree["period_credit"])
{
$closing = format_currency($tree["opening_debit"] + $tree["period_debit"] - $tree["opening_credit"] - $tree["period_credit"], 2) . " Dr.";
}
elseif ($tree["opening_credit"] + $tree["period_credit"] > $tree["opening_debit"] + $tree["period_debit"])
{
$closing = format_currency($tree["opening_credit"] + $tree["period_credit"] - $tree["opening_debit"] - $tree["period_debit"], 2) . " Cr.";
}
else
{
$closing = "0";
}
echo $closing;
//calculate all opeing and closing debit & credit.
if ($tree["opening_debit"] + $tree["period_debit"] > $tree["opening_credit"] + $tree["period_credit"])
{
$total_closing_debit += ($tree["opening_debit"] + $tree["period_debit"] - $tree["opening_credit"] - $tree["period_credit"]);
}
if ($tree["opening_credit"] + $tree["period_credit"] > $tree["opening_debit"] + $tree["period_debit"])
{
$total_closing_credit += ($tree["opening_credit"] + $tree["period_credit"] - $tree["opening_debit"] - $tree["period_debit"]);
}
?>
</span>
<?
if(count($tree["children"]) > 0)
{
//make_children_tree();
}
?>
</li>
<?
}
}
}
?>
i solved myself here what approach i choose i extract children array into other array and on that array i use my recursion to do magic.
<? $array = $trial_tree["children"]; ?>
$trial_balance_tree = $this->trees;
$total_opening_debit = 0;
$total_opening_credit = 0;
$total_debit = 0;
$total_credit = 0;
$total_closing_debit = 0;
$total_closing_credit = 0;
$total_opening = 0;
$total_closing = 0;
function makeListItems($a) {
global $total_opening_debit,$total_opening_credit,$total_credit,$total_debit,$total_closing_debit,$total_closing_credit,$total_opening,$total_closing;
$out = '';
foreach($a as $val) {
//print_r($key); echo is_array($val);exit;
if($val["id"] > 0)
{
$out .= '<li>';
$out .= "<span class='first'>" . $val["name"] . "</span>";
$out .= "<span class='other'>";
if ($val["opening_debit"] > $val["opening_credit"])
{
$out .= format_currency($val["opening_debit"] - $val["opening_credit"], 2) . " Dr.";
}
elseif ($val["opening_credit"] > $val["opening_debit"])
{
$out .= format_currency($val["opening_credit"] - $val["opening_debit"], 2) . " Cr.";
}
else
{
$out .= "0";
}
$total_opening_debit += $val["opening_debit"];
$total_opening_credit += $val["opening_credit"];
$out .= "</span>";
$out .= "<span class='other'>";
if($val["period_debit"]<>"" && $val["period_debit"]<>"0")
{
$out .= format_currency($val["period_debit"], 2);
$total_debit += $val["period_debit"];
}
else
{
$out .= 0;
}
$out .= "</span>";
$out .= "<span class='other'>";
if($val["period_credit"]<>"" && $val["period_credit"]<>"0")
{
$out .= format_currency($val["period_credit"], 2);
$total_credit += $val["period_credit"];
}
else
{
$out .= 0;
}
$out .= "</span>";
$out .= "<span class='other'>";
if ($val["opening_debit"] + $val["period_debit"] > $val["opening_credit"] + $val["period_credit"])
{
$closing = format_currency($val["opening_debit"] + $val["period_debit"] - $val["opening_credit"] - $val["period_credit"], 2) . " Dr.";
}
elseif ($val["opening_credit"] + $val["period_credit"] > $val["opening_debit"] + $val["period_debit"])
{
$closing = format_currency($val["opening_credit"] + $val["period_credit"] - $val["opening_debit"] - $val["period_debit"], 2) . " Cr.";
}
else
{
$closing = "0";
}
$out .= $closing;
//calculate all opeing and closing debit & credit.
if ($val["opening_debit"] + $val["period_debit"] > $val["opening_credit"] + $val["period_credit"])
{
$total_closing_debit += ($val["opening_debit"] + $val["period_debit"] - $val["opening_credit"] - $val["period_credit"]);
}
if ($val["opening_credit"] + $val["period_credit"] > $val["opening_debit"] + $val["period_debit"])
{
$total_closing_credit += ($val["opening_credit"] + $val["period_credit"] - $val["opening_debit"] - $val["period_debit"]);
}
$out .= "</span>";
if(array_key_exists('children', $val)) {
$out .= makeList($val['children']);
}
$out .= '</li>';
}
}
return $out;
}
function makeList($a) {
$out = '<ul>';
$out .= makeListItems($a);
$out .= '</ul>';
return $out;
}
?>
<table style="width:100%;background-color: #A5C6DB;">
<tr>
<th class="table_first" style="width:42.5%;">Ledger Name</th>
<th class="table_other" style="width:14.7%;">Opening</th>
<th class="table_other" style="width:14.7%;">Debit</th>
<th class="table_other" style="width:14.7%;">Credit</th>
<th class="table_other" style="width:15%;">Closing</th>
</tr>
</table>
<?
echo "<div id='trial_balance_tree'>";
echo makeList($trial_balance_tree);
echo "</div>";
Now my view look like this and thats exactly i want.

automatic selected dropdown date PHP (with joomla)

at first sorry for my english. I have a problem with my website. I have 2 dropdown with date see the image (inizio=start, fine=end). I would like that when I click the START DATE, the END DATE changes (automatically) to one hour more than the start date. For example: In "inizio" I select the following date: 16 agosto (August) 2017 14:30, the END DATE should changes automatically in 16 agosto 2017 15:30. Default.php:
<tr height="50px">
<td align="center" style="border-color:white; border:0px; background-color:#F8F9FA;"><br /><b><font size="+1">Inizio</font></b></td>
<td align="center" style="border-color:white; border:0px; background-color:#F8F9FA;"><br />' . $this->helper->dateTimePicker("inizio", "DATETIME") . '</td>
</tr>
<tr height="50px">
<td align="center" style="border-color:white; border:0px; background-color:#F8F9FA;"><b><font size="+1">Fine</font></b></td>
<td align="center" style="border-color:white; border:0px; background-color:#F8F9FA;">' . $this->helper->dateTimePicker("fine", "DATETIME") . '</td>
</tr>
Method dataTimePicker:
function dateTimePicker($dpname, $mode = "DATE") // MODES: "DATE" or "DATETIME"
{
$control = "";
$anni_da_visualizzare = 2;
if ($mode == "DATE" || $mode == "DATETIME")
{
$control .= '<select name="giorno_'.$dpname.'">';
for ($i = 1; $i <= 31; $i++)
{
if ($i == date("j"))
{
$control .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
}
else
{
$control .= '<option value="'.$i.'">'.$i.'</option>';
}
}
$control .= '</select>';
//=================================
$control .= " ";
$mesi = array("Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre");
$control .= '<select name="mese_'.$dpname.'">';
for ($i = 1; $i <= 12; $i++)
{
if ($i == date("n"))
{
$control .= '<option value="'.$i.'" selected="selected">'.$mesi[$i-1].'</option>';
}
else
{
$control .= '<option value="'.$i.'">'.$mesi[$i-1].'</option>';
}
}
$control .= '</select>';
//=================================
$control .= " ";
$control .= '<select name="anno_'.$dpname.'">';
$inizio = date("Y");
$fine = date("Y") + $anni_da_visualizzare;
for ($i = $inizio; $i <= $fine; $i++)
{
if ($i == date("Y"))
{
$control .= '<option value="'.$i.'" selected="seected">'.$i.'</option>';
}
else
{
$control .= '<option value="'.$i.'">'.$i.'</option>';
}
}
$control .= '</select>';
//=================================
$control .= " ";
if ($mode == "DATETIME")
{
//H - ore_$dpname !
$control .= '<select name="ore_'.$dpname.'">';
for ($i = 0; $i <= 23; $i++)
{
if ($i == date("G"))
{
$control .= '<option value="'.$i.'" selected="selected">'.($i < 0 ? '0'.$i : $i).'</option>';
}
else
{
$control .= '<option value="'.$i.'">'.($i < 10 ? '0'.$i : $i).'</option>';
}
}
$control .= '</select>';
//=================================
$control .= " ";
//Minutes- minuti_$dpname !
$control .= '<select name="minuti_'.$dpname.'">';
for ($i = 0; $i <= 3; $i++)
{
if (intval(date("i")) < ($i*15) && intval(date("i")) > (($i*15) - 15))
$control .= '<option value="'.($i*15).'" selected="selected">'.($i == 0 ? '00' : (15*$i)).'</option>';
else
$control .= '<option value="'.($i*15).'">'.($i == 0 ? '00' : (15*$i)).'</option>';
}
$control .= '</select>';
//=================================
$control .= " ";
}
return $control."<br />";
}
else
{
return "{<u>dateTimePicker ERROR:</u> modalità non valida}";
}
}
Have a look at this documentation
It would be best to use jquery for this. You would have to add something like $(".time2").val('2'); within the onchange of time1. Where the amount in val is equal to the time plus 1 hour.
Time1 - being the first date and time class
Time2 - being the second date and time class

Foreach Loop only uses last value [duplicate]

This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
Hi I am using the Calendar Code u can find down in the code. Now I am using Sql to get some days I want to mark in the calendar. In the foreach loop u can see me using the array $tage.
When I print_r($tage) it gives me following Information: Array ( [0] => 9 [1] => 8 [2] => 8 [3] => 8 [4] => 8 [5] => 11 )
Maybe there is a Problem with the returning values, but using only the unique values was not possible either.
Fyi the only highlight I always get is the last value 11.
I think the whole issue comes down to the combination of while foreach and elseif. I can't find any Solution to this. Maybe someone figures it out.
Thanks :)
<?php
error_reporting();
ini_set('display_errors', 1);
setlocale(LC_TIME, "de_DE");
class Calendar{
private $month;
private $year;
private $daysofweek;
private $numdays;
private $date_info;
private $day_of_week;
private $tnr;
public function __construct($month,$year,$days_of_week =array('So','Mo','Di','Mi','Do','Fr','Sa')){
$this->month =$month;
$this->year =$year;
$this->days_of_week =$days_of_week;
$this->num_days =cal_days_in_month(CAL_GREGORIAN, $this->month, $this->year);
$this->date_info =getdate(strtotime('first day of', mktime(0,0,0,$this->month,1,$this->year)));
$this->day_of_week =$this->date_info['wday'];
$this->monat = date("n", mktime(0, 0, 0, $this->month, 1, $this->year));
}
public function show($tnr) {
$monate = array(1=>"Januar",
2=>"Februar",
3=>"März",
4=>"April",
5=>"Mai",
6=>"Juni",
7=>"Juli",
8=>"August",
9=>"September",
10=>"Oktober",
11=>"November",
12=>"Dezember");
include '../include/myt.php';
// WERT 0 entfernen
// GRÖße des ARRAY
$size =sizeof($tnr);
$now_mon= $this->monat;
foreach($tnr as $tnrs){
$sql= "SELECT * FROM termin WHERE nr = '$tnrs' AND monat ='$now_mon' ";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$tagdata = $row['tag'];
if($tagdata == ""){
"";
} else {
$tage[] = $tagdata;
}
}
$output= '<table id="table'. $this->monat . '" class="table table-striped">';
$output .= '<thead id="head'. $this->monat . '" style="text-align:center">'. $monate[$this->monat] . ' ' . $this->year . '</thead>';
$output .= '<tr>';
foreach( $this->days_of_week as $day)
{
$output .= '<th class="header center">' . $day . '</th>';
}
$output .= '</tr><tr>';
if($this->day_of_week > 0){
$output .= '<td colspan="' . $this->day_of_week . '"></td>';
}
$current_day =1;
while ( $current_day <= $this->num_days){
if($this->day_of_week ==7){
$this ->day_of_week =0;
$output .= '</tr></tr>';
}
///PROBLEM
print_r($tage);
foreach($tage as $tag){
if($current_day == $tag){
$current='style ="background: black;"';
} else {
$current= '';
}
}
///PROBLEM
$output .='<td class="day"'.$current.'>' . $current_day . '</td>';
$current_day++;
$this->day_of_week++;
}
if($this->day_of_week != 7){
$remaining_days = 7 - $this->day_of_week;
$output .= '<td colspan="' . $remaining_days . '"></td>';
}
$output .= '</tr>';
$output .= '</table>';
echo $output;
}
}
?>
Change your foreach loop as below:
foreach($tnr as $tnrs) {
$sql= "SELECT * FROM termin WHERE nr = '$tnrs' AND monat ='$now_mon' ";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$tagdata = $row['tag'];
if(!empty($tagdata)) {
$tage[] = $tagdata;
}
}
Can you please check at line $output .='<td class="day"'.$current.'>' . $current_day . '</td>';
It should be $output .='<td class="day"'.$current.'">' . $current_day . '</td>';, You are forgot to add ".
May be it is help you.

Show first letter of a list once?

I have a list of directory name and need to get the first letter from each name and just display it once before the start of that lettered group ie;
what I have:
1
2
3
4
5
Aberdeen
Arundel
Aberyswith
Bath
Bristol
Brighton
Cardiff
coventry
what I would like:
#
1
2
3
4
5
A
Aberdeen
Arundel
Aberyswith
B
Bath
Bristol
Brighton
C
Cardiff
coventry
function htmlDirList($subdirs) {
global $z_self, $z_img_play, $z_img_lofi, $z_img_more, $z_admin,
$z_img_down, $z_img_new, $zc;
$now = time();
$diff = $zc['new_time']*60*60*24;
$num = 0;
$dir_list_len = $zc['dir_list_len'];
if ($zc['low']) { $dir_list_len -= 2; }
$html = "";
$checkbox = ($z_admin || ($zc['playlists'] && $zc['session_pls']));
/**/
$row = 0;
$items = sizeof($subdirs);
$cat_cols = "2";
$rows_in_col = ceil($items/$cat_cols);
if ($rows_in_col < $cat_cols) { $cat_cols = ceil($items/$rows_in_col); }
$col_width = round(100 / $cat_cols);
$html = "<table width='600'><tr>";
$i = 0;
/**/
foreach ($subdirs as $subdir => $opts) {
if ($row == 0) {
$class = ($cat_cols != ++$i) ? ' class="z_artistcols"' : '';
$html .= "<td $class valign='top' nowrap='nowrap' width='$col_width%'>";
}
/*$currentleter = substr($opts, 0 , 1);
if($lastletter != $currentleter){
echo $currentleter;
$lastletter = $currentleter;
}*/
if($alphabet != substr($opts,0,1)) {
echo strtoupper(substr($opts,0,1)); // add your html formatting too.
$alphabet = substr($opts,0,1);
}
$dir_len = $dir_list_len;
$dir = false;
$image = $opts['image'];
$new_beg = $new_end = "";
if (substr($subdir, -1) == "/") {
$dir = true;
$subdir = substr($subdir, 0, -1);
}
$path_raw = getURLencodedPath($subdir);
$href = "<a href='$path_raw";
if (!$dir) {
if ($zc['download'] && $zc['cmp_sel']) { $html .= "$href/.lp&l=8&m=9&c=0'>$z_img_down</a> "; }
if ($zc['play']) { $html .= "$href&l=8&m=0'>$z_img_play</a> "; }
if ($zc['low'] && ($zc['resample'] || $opts['lofi'])) { $html .= "$href&l=8&m=0&lf=true'>$z_img_lofi</a> "; }
if ($checkbox) { $html .= "<input type='checkbox' name='mp3s[]' value='$path_raw/.lp'/> "; }
$num++;
if ($zc['new_highlight'] && isset($opts['mtime']) && ($now - $opts['mtime'] < $diff)) {
$dir_len -= 5;
if ($z_img_new) {
$new_end = $z_img_new;
} else {
$new_beg = $zc['new_beg'];
$new_end = $zc['new_end'];
}
}
}
$title = formatTitle(basename($subdir));
if (strlen($title) > $dir_len) {
$ht = " title=\"$title.\"";
$title = substr($title,0,$dir_len).$opts['mtime']."...";
} else {
$ht = "";
}
if ($zc['dir_list_year']) {
$di = getDirInfo($subdir);
if (!empty($di['year'])) $title .= " (".$di['year'].")";
}
$html .= "$href'$ht>$new_beg$title$new_end</a><br />";
$row = ++$row % $rows_in_col;
if ($row == 0) { $html .= "</td>"; }
}
if ($row != 0) $html .= "</td>";
$html .= "</tr></table>";
$arr['num'] = $num;
$arr['list'] = $html;
return $arr;
}
I need help to get work.
The following will display the list of directories, beginning each group with a first letter as beginning of the group (see codepad for proof):
(this assumes $dirs is array containing the names)
$cur_let = null;
foreach ($dirs as $dir) {
if ($cur_let !== strtoupper(substr($dir,0,1))){
$cur_let = strtoupper(substr($dir,0,1));
echo $cur_let."\n";
}
echo $dir . "\n";
}
You just need to add some formatting on your own, suited to your needs.
Edit:
Version grouping under # sign entries that begin with a number, can look like that:
$cur_let = null;
foreach ($dirs as $dir) {
$first_let = (is_numeric(strtoupper(substr($dir,0,1))) ? '#' : strtoupper(substr($dir,0,1)));
if ($cur_let !== $first_let){
$cur_let = $first_let;
echo $cur_let."\n";
}
echo $dir . "\n";
}
Please see codepad as a proof.
Is this what you are looking for?
<?php
$places = array(
'Aberdeen',
'Arundel',
'Aberyswith',
'Bath',
'Bristol',
'Brighton',
'Cardiff',
'coventry'
);
$first_letter = $places[0][0];
foreach($places as $p)
{
if(strtolower($p[0])!=$first_letter)
{
echo "<b>" . strtoupper($p[0]) . "</b><br/>";
$first_letter = strtolower($p[0]);
}
echo $p . "<br/>";
}
?>
Prints:
A
Aberdeen
Arundel
Aberyswith
B
Bath
Bristol
Brighton
C
Cardiff
coventry
My approach would be to generate a second array that associates the first letter to the array of names that begin with that letter.
$dirs; // assumed this contains your array of names
$groupedDirs = array();
foreach ($dirs as $dir) {
$firstLetter = strtoupper($dir[0]);
$groupedDirs[$firstLetter][] = $dir;
}
Then, you can iterate on $groupedDirs to print out the list.
<?php foreach ($groupedDirs as $group => $dirs): ?>
<?php echo $group; ?>
<?php foreach ($dirs as $dir): ?>
<?php echo $dir; ?>
<?php endforeach; ?>
<?php endforeach; ?>
This allows for a clean separation between two separate tasks: figuring out what the groups are and, secondly, displaying the grouped list. By keeping these tasks separate, not only is the code for each one clearer, but you can reuse either part for different circumstances.
Use something like this, change it to output the HTML the way you want thouugh:
sort($subdirs);
$count = count($subdirs);
$lastLetter = '';
foreach($subdirs as $subdir => $opts){
if(substr($subdir,0,1) !== $lastLetter){
$lastLetter = substr($subdir,0,1);
echo '<br /><div style="font-weight: bold;">'.strtoupper($lastLetter).'</div>';
}
echo '<div>'.$subdir.'</div>';
}
EDIT
Just realized $subdir is associative, made the change above:

Pagination not taking value to second page?

$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '')
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
echo "";
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
Pagination is working correctly for select $today. Here pagination is not taking value to second page in the case of select $mydate. If second page of $mydate clicks, again going to $today. ie Second click is not posting $mydate to next page. How can I take the value to second page?
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>
function pagination in your code is not returning the resulting mysql query resource, and your code is not receiving that from the pagination function call
you need
to add return $pg_result; in your pagination function
and add $result=pagination(....
Edit:
Sorry, I noticed you added pg_result to global, which does not need return and the solution I said, but you don't need mysql_query and fetch before that and I don't see where you print the results. there is only echo "", you can try the one I edited last, and see if it works for you.
Edit:
$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
//$result=mysql_query($sql);
$pg_result=pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '' && is_resource($pg_result))
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
var_dump($data);
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
return $pg_result;
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>
Looks like you're mixing up the concept of $_POST and $_GET.
By having your pagination links point to '<a href="'.$pg_page_name.'?page_id='.$i . $pg_user_param.'"... You should be intercepting $_GET['page_id'] before you make your SQL query.
Your top code references $_POST['datepicker'] but you don't mention a form anywhere and your pagination links certainly aren't posting that data in your example.
You should use $pg_param = ""; to pass your own query parameters. Ex: &date=$date_value:
$pg_param = "&date=$date_value";

Categories