Show first letter of a list once? - php

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:

Related

I'm trying to convert an array to XML but I am failing to get it 100% correct

I need to output the response from the database in XML. So far I have gotten it to output this:
The outermost tag needs to match the name of the action query, it'll either be <courses> or <students>.
Here is my code:
<?php
require_once('./database.php');
if (isset($_GET['format'])) {
$format = filter_var($_GET['format']);
}
if (isset($_GET['action'])) {
$action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
$tableName = "sk_$action";
}
$query = "SELECT * FROM $tableName";
if (isset($_GET['course'])) {
$course = filter_input(INPUT_GET, 'course');
$query .= " WHERE courseID = :course";
}
function arrayToXml($arr, $i = 1, $flag = false)
{
$sp = "";
for ($j = 0; $j <= $i; $j++) {
$sp .= " ";
}
foreach ($arr as $key => $val) {
echo "$sp<" . $key . ">";
if ($i == 1) echo "\n";
if (is_array($val)) {
if (!$flag) {
echo "\n";
}
arrayToXml($val, $i + 5);
echo "$sp</" . $key . ">\n";
} else {
echo "$val" . "</" . $key . ">\n";
}
}
}
$statement = $db->prepare($query);
$statement->bindValue(':course', $course);
$statement->execute();
$response = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
if ($format == 'json') {
echo json_encode($response);
}
if ($format == 'xml') {
arrayToXml($response, 1, true);
}
I'm pretty new to PHP and have never worked with XML. All help is appreciated. Thanks.
function arrayToXml($arr, $collectionTag, $singleTag) {
$collection = new SimpleXMLElement("<$collectionTag/>");
foreach ($arr as $row) {
$element = $root->addChild($singleTag);
foreach ($row as $tag => $value) {
$element->addChild($tag, $value);
}
}
return $collection;
}
$courses = arrayToXml($response, 'courses', 'course');
echo $courses->asXML();
Tested with PHP 7.1.23. Output:
<?xml version="1.0"?>
<courses>
<course><courseID>cs601</courseID><courseName>Web Application Development</courseName></course>
<course><courseId>cs602</courseId><courseName>Server-Side Application Development</courseName></course>
<course><courseId>cs701</courseId><courseName>Rich Internet Application Development</courseName></course>
</courses>
(I added newlines because by default it doesn't add any.)

what are the different ways for this code to work

The following is part of a personal budgeting program I'm writing.
This code pulls line item information from multiple tables and writes it into an array and then displays the information by transid => family => category => lineItems. Everything works, and I get the results I want out of it. My question is if there is a more efficient way to accomplish this task?
Since this is a personal program, I'm only asking so that I can improve my coding abilities.
<?php
include ('../cfg/connect.php');
$s = " : ";
$br = "<br>";
$ul = "<ul>";
$li = "<li>";
$_ul = "</ul>";
$_li = "</li>";
$data = [];
$itemCount = 0;
$arrayItemCount = 0;
$categoryQry = "SELECT a.itemQty, b.transDate, b.transID, b.amount, a.itemPrice, a.itemCategory, c.catFamily, a.itemName, a.itemSource FROM budget.lineItems AS a JOIN budget.quickEntry AS b ON a.transID = b.transID JOIN budget.categories AS c ON a.itemCategory = c.catName WHERE b.processed = 'y' ORDER BY c.catFamily, c.catName, b.transDate";
$categories = $conn->prepare ($categoryQry);
$categories->execute ();
$categories->store_result ();
$categories->bind_result ($itemQty, $transDate, $transID, $totalPrice, $itemPrice, $category, $family, $itemName, $source);
while ($categories->fetch ()) {
if (!isset($data[$transID]['amount'])) {
$data[$transID]['amount'] = 0;
}
if (!isset($data[$transID]['line'])) {
$data[$transID]['line'] = '';
}
if (!isset($data[$transID]['line'][$family]['amount'])) {
$data[$transID]['line'][$family]['amount'] = 0;
}
if (!isset($data[$transID]['line'][$family]['line'])) {
$data[$transID]['line'][$family]['line'] = '';
}
if (!isset($data[$transID]['line'][$family]['line'][$category]['amount'])) {
$data[$transID]['line'][$family]['line'][$category]['amount'] = 0;
}
if (!isset($data[$transID]['line'][$family]['line'][$category]['line'])) {
$data[$transID]['line'][$family]['line'][$category]['line'] = '';
}
$itemCount++;
$qtyPrice = $itemPrice * $itemQty;
$data[$transID]['amount'] += $qtyPrice;
$data[$transID]['transDate'] = $transDate;
$data[$transID]['source'] = $source;
$data[$transID]['line'][$family]['amount'] += $qtyPrice;
$data[$transID]['line'][$family]['line'][$category]['amount'] += $qtyPrice;
$data[$transID]['line'][$family]['line'][$category]['line'][$itemName] = ['itemQty' => $itemQty, 'itemPrice' => $itemPrice];
}
foreach ($data as $transID => $transValue) {
echo $transID .$s.$transValue['transDate'].$s.$transValue['source'].$s.$transValue['amount']. $ul;
foreach ($transValue['line'] as $category => $categoryValue) {
echo $li . $category .$s.$categoryValue['amount']. $ul;
foreach ($categoryValue['line'] as $line => $lineValue) {
echo $li . $line .$s.$lineValue['amount']. $ul;
foreach ($lineValue['line'] as $item => $details) {
echo $li . $item .$s . $details['itemQty'] . $s . $details['itemPrice'] . $_li;
}
echo $_ul . $_li;
}
echo $_ul . $_li;
}
echo $_ul . $br;
}

Displaying SQL-data in a table

A few months ago, I made a system where people could upload a picture and then those pictures would be displayed in a table with 4 columns.
Now I am working on a project (to practice my php, I am still learning it) and I would like to use a similar system as below but it should display data from a database.
The result I was trying to achieve is the data being displayed in 2 columns.
if ($handle = opendir('images/')) {
$bool = true;
while ($bool) {
$td = 1;
echo '<tr>';
while ($td < 4) {
$file = readdir($handle);
if ($file != '.' && $file != '..' && $file != '.DS_Store') {
echo '<td>';
if ($file) {
echo '<img src="images/'.$file.
'">';
} else {
$bool = false;
}
echo '</td>';
$td++;
}
}
echo '</tr>';
}
}
closedir($handle);
For anyone looking for the answer:
$query = "SELECT * FROM webshop";
if($query_run = mysql_query($query)) {
$bool = true;
echo '<table>';
while($bool) {
$td = 0;
echo '<tr>';
while($td < 2) {
if($fetch = mysql_fetch_assoc($query_run)) {
echo '<td>';
$title = $fetch['title'];
$info = $fetch['info'];
/* Commented out for now, will be implemented later
$image = $fetch['image'];
$price = $fetch['price'];
*/
echo $title;
} else {
$bool = false;
}
echo '</td>';
$td++;
}
echo '</tr>';
}
echo '</table>';
}

Group MySQL results into blocks of A-Z in PHP

I have a list of thousands of results and I want to group them alphanumerically for example, I need it to be like this:
<h1>0-9</h1>
<ul>
<li>011example</li>
<li>233example</li>
<li>65example</li>
</ul>
<h1>A</h1>
<ul>
<li>albert</li>
<li>alfred</li>
<li>annie</li>
</ul>
<h1>B</h1>
<ul>
<li>ben</li>
<li>bertie</li>
<li>burt</li>
</ul>
But I can't work out how to split or group my results into 0-9 and A-Z.
Currently I have:
<?php
$get_az = mysql_query("SELECT custom_22 FROM db_table1");
echo '<ul>';
while ($row = mysql_fetch_assoc($get_az)) {
$getfirstletter = substr($row['custom_22'], 0,1);
$name = $row['custom_22'];
echo '<h1>'.$getfirstletter.'</h1>';
echo '<li>'.$name.'</li>';
}
echo '</ul>';
?>
Order by the name and handle each letter one by one.
$get_az = mysql_query("SELECT custom_22 FROM db_table1 ORDER BY custom_22 ASC");
$current_first_letter = null;
while ($row = mysql_fetch_assoc($get_az)) {
$first_letter = strtolower(substr($row['custom_22'], 0, 1));
if (preg_match("/[0-9]/", $first_letter)) { // detect digits
$first_letter = "0-9";
}
if ($first_letter !== $current_first_letter) {
if ($current_first_letter !== null) {
echo '</ul>';
}
echo '<h1>' . $first_letter . '</h1>';
echo '<ul>';
}
$current_first_letter = $first_letter;
echo '<li>' . htmlentities($row['custom_22']) . '</li>';
}
if ($current_first_letter !== null) {
echo '</ul>';
}
I would do it this readable way:
$get_az = mysql_query('SELECT custom_22 FROM db_table1 ORDER BY custom_22');
$groups = array();
split results to groups
while ($row = mysql_fetch_assoc($get_az)) {
$firstLetter = strtolower(substr($row['custom_22'], 0, 1));
check for digits
if (is_numeric($firstLetter)) {
$firstLetter = '0-9';
}
if (isset($groups[$firstLetter]) === false) {
$groups[$firstLetter] = array();
}
$groups[$firstLetter][] = $row['custom_22'];
}
simply iterate over groups and echoes it
foreach ($groups as $h1 => $items) {
echo sprintf('<h1>%s</h1>', strtoupper(htmlspecialchars($h1)));
echo '<ul>';
foreach ($items as $item) {
echo sprintf('<li>%s</li>', htmlspecialchars($item));
}
echo '</ul>';
}

Getting Mysql field from an array

I have the following script to display files inside a directory
<?PHP
# The current directory
$directory = dir("./");
# If you want to turn on Extension Filter, then uncomment this:
$allowed_ext = array(".deb", ".ext", ".ext", ".ext", ".ext", ".ext");
$do_link = TRUE;
$sort_what = 0; //0- by name; 1 - by size; 2 - by date
$sort_how = 0; //0 - ASCENDING; 1 - DESCENDING
# # #
function dir_list($dir){
$i=0;
$dl = array();
if ($hd = opendir($dir)) {
while ($sz = readdir($hd)) {
if (preg_match("/^\./",$sz)==0) $dl[] = $sz;$i.=1;
}
closedir($hd);
}
asort($dl);
return $dl;
}
if ($sort_how == 0) {
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return -1;
else return 1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return -1;
else return 1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return -1;
else return 1;
}
}else{
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return 1;
else return -1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return 1;
else return -1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return 1;
else return -1;
}
}
##################################################
# Getting The information
##################################################
$i = 0;
while($file=$directory->read()) {
$file = strtolower($file);
$ext = strrchr($file, '.');
if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
{
// dump
}
else {
$temp_info = stat($file);
$new_array[$i][0] = $file;
$new_array[$i][1] = $temp_info[7];
$new_array[$i][2] = $temp_info[9];
$new_array[$i][3] = date("F d, Y", $new_array[$i][2]);
$i = $i + 1;
}
}
$directory->close();
##################################################
# Sorting the information
#################################################
switch ($sort_what) {
case 0:
usort($new_array, "compare0");
break;
case 1:
usort($new_array, "compare1");
break;
case 2:
usort($new_array, "compare2");
break;
}
###############################################################
# Displaying the information
###############################################################
$i2 = count($new_array);
$i = 0;
echo "<table class='CSSTableGenerator'>
<tr>
<td width=290>File name (Download)</td>
<td align=center width=70>Downloads</td>
<td align=center width=70>Depiction</td>
<td align=center width=50>Size</td>
<td align=center width=85>Modified</td>
</tr>";
for ($i=0;$i<$i2;$i++) {
if (!$do_link) {
$line = "<tr><td>" . $new_array[$i][0];
$line .= '</td><td>Depiction</td>';
$line .= "<td>" . number_format(($new_array[$i][1]/1024)) . " KB</td>";
$line .= "<td>" . $new_array[$i][3] . "</td></tr>";
}else{
$line = '<tr><td align=left ><A class="ex1" HREF="' .
$new_array[$i][0] . '">' .
$new_array[$i][0] .
"</A></td>";
$line .= '<td> </td>';
$line .= '<td>Depiction</td>';
$line .= "<td>" . number_format(($new_array[$i][1]/1024)) . " KB</td>";
$line .= "<td>" . $new_array[$i][3] . "</td></tr>";
}
echo $line;
}
echo "</table>";
?>
The output looks like that:
I am trying to fill the downloads column by getting the download counts of each file from mysql table
So i am facing 2 issues here:
How to get the stats using the array of the files $new_array[$i][0]
How can i then add this mysql query output inside $line .= '<td> </td>';
I have tried getting the stats from the table using this:
include("../config.php");
$query = "SELECT stats FROM download WHERE filename='$new_array[$i][0]'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$line .= '<td>' . $row['stats'] . '</td>';
}
but it didn't work, i think the issue is with the array $new_array[$i][0] because i tried writing a filename filename='com.name.app3_2.2-1_iphoneos-arm.deb' and i got the stats of this file
In your "getting the information part", you must initialise your arrays thusly:
##################################################
# Getting The information
##################################################
$i = 0;
$new_array = array();
while($file=$directory->read()) {
$file = strtolower($file);
$ext = strrchr($file, '.');
if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
{
// dump
}
else {
$new_array[$i] = array();
$temp_info = stat($file);
$new_array[$i][0] = $file;
$new_array[$i][1] = $temp_info[7];
$new_array[$i][2] = $temp_info[9];
$new_array[$i][3] = date("F d, Y", $new_array[$i][2]);
$i = $i + 1;
}
}
$directory->close();
##################################################
In addition, I have noted that your line:
$query = "SELECT stats FROM download WHERE filename='$new_array[$i][0]'";
Would cause $query to be equal to:
SELECT stats FROM download WHERE filename='Array[0]'
When $i is 0.
What you should do is use the mysqli library thusly:
$mysqli = new mysqli("example.com", "user", "password", "database");
$query = "SELECT stats FROM download WHERE filename=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $new_array[$i][0]);
$stmt->execute();
$stmt->bind_result($stats);//stats turns into a reference by default.
while($stmt->fetch()) { //$stats now contains the stats
$line .= '<td>'. htmlentities($stats).'</td>';
}
To deal with the problem of missing cells you just described, you might try:
$mysqli = new mysqli("example.com", "user", "password", "database");
$query = "SELECT stats FROM download WHERE filename=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $new_array[$i][0]);
$stmt->execute();
$stmt->bind_result($stats);//stats turns into a reference by default.
$fetched = false;
while($stmt->fetch()) { //$stats now contains the stats
$line .= '<td>'. htmlentities($stats).'</td>';
$fetched = true;
}
if(!$fetched) {
$line .= '<td></td>'
}

Categories