Hot to feed php function - php

Hi I am try to display icecat product data and I am a complete php newbie, I have tracked down a code snippet that I believe should do the job, It says that It requires that you feed the function with an EAN product number.
Could someone please give me an example of what this means as I have no idea, here is a EAN Product number EAN/UPC code:0885909481842
Here is the snippet code I am trying to use.
function getICEcatProductSpecs($ean, $drawdescription = 0, $drawpicture = 0)
{
// Username and password for usage with ICEcat
$username = "Your ICEcat username goes here";
$password = "Your ICEcat password goes here";
// Return 0 and exit function if no EAN available
if($ean == null)
{
return 0;
}
// Get the product specifications in XML format
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode($username.":".$password)
)
));
$data = file_get_contents('http://data.icecat.biz/xml_s3/xml_server3.cgi?ean_upc='.$ean.';lang=nl;output=productxml', false, $context);
$xml = new SimpleXMLElement($data);
// Create arrays of item elements from the XML feed
$productPicture = $xml->xpath("//Product");
$productDescription = $xml->xpath("//ProductDescription");
$categories = $xml->xpath("//CategoryFeatureGroup");
$spec_items = $xml->xpath("//ProductFeature");
//Draw product specifications table if any specs available for the product
if($spec_items != null)
{
$categoryList = array();
foreach($categories as $categoryitem) {
$catId = intval($categoryitem->attributes());
$titleXML = new SimpleXMLElement($categoryitem->asXML());
$title = $titleXML->xpath("//Name");
$catName = $title[0]->attributes();
//echo $catId . $catName['Value']. "<br />";
$categoryList[$catId] = $catName['Value'];
}
$specs = "<table class='productspecs'>";
$i = 0;
$drawnCategories = array();
foreach($spec_items as $item) {
$specValue = $item->attributes();
$titleXML = new SimpleXMLElement($item->asXML());
$title = $titleXML->xpath("//Name");
$specName = $title[0]->attributes();
$specCategoryId = intval($specValue['CategoryFeatureGroup_ID']);
if($specName['Value'] != "Source data-sheet")
{
$class = $i%2==0?"odd":"even";
$specs .= "<tr class='".$class."'>
<td>
<table>";
if(!in_array($specCategoryId, $drawnCategories))
{
$specs .= " <tr class='speccategory'>
<th><h3>".$categoryList[$specCategoryId]."</h3></th>
</tr>";
$drawnCategories[$i] = $specCategoryId;
}
$specs .= " <tr>
<th>".utf8_decode($specName['Value']).":</th>
</tr>
<tr>
<td>";
if($specValue['Presentation_Value'] == "Y")
{
$specs .= "Ja <img src='".SCRIPT_ROOT."images/check_green.png' alt='Ja' />";
}
else if($specValue['Presentation_Value'] == "N")
{
$specs .= "Nee <img src='".SCRIPT_ROOT."images/check_red.png' alt='Nee' />";
}
else
{
$specs .= str_replace('\n', '<br />', utf8_decode($specValue['Presentation_Value']));
}
$specs .= "</td>
</tr>
</table>
</td>
</tr>";
}
$i++;
}
$specs .= "</table>";
//Draw product description and link to manufacturer if available
if( $drawdescription != 0)
{
foreach($productDescription as $item) {
$productValues = $item->attributes();
if($productValues['URL'] != null)
{
$specs .= "<p id='manufacturerlink'><a href='".$productValues['URL']."'>Productinformation from manufacturer</a></p>";
}
if($productValues['LongDesc'] != null)
{
$description = utf8_decode(str_replace('\n', '', $productValues['LongDesc']));
$description = str_replace('<b>', '<strong>', $description);
$description = str_replace('<B>', '<strong>', $description);
$description = str_replace('</b>', '</strong>', $description);
$specs .= "<p id='manudescription'>".$description."</p>";
}
}
}
//Draw product picture if available
if( $drawdescription != 0)
{
foreach($productPicture as $item) {
$productValues = $item->attributes();
if($productValues['HighPic'] != null)
{
$specs .= "<div id='manuprodpic'><img src='".$productValues['HighPic']."' alt='' /></div>";
}
}
}
return $specs;
}
else
{
return 0;
}
}
Any advice will be very appreciated thx in advance Peter

My understanding is that it's saying that if you call this function you should pass EAN parameter to it, like this:
getICEcatProductSpecs("0885909481842", 0, 0);

Related

moddle change in table summary of exam

I use Moodle 3.9.1+ . I want to change summary exam table to div to be able to show the each question and its situation beside each-other like below. I want to have each 5 question in a row in fact. As I know it's not possible to do so with table and because of that I want to use div to be able to do so with css.
I found the file /mod/quiz/renderer.php has a function with below code that makes the summary exam table.
public function summary_table($attemptobj, $displayoptions) {
// Prepare the summary table header.
$table = new html_table();
$table->attributes['class'] = 'generaltable quizsummaryofattempt boxaligncenter';
$table->head = array(get_string('question', 'quiz'), get_string('status', 'quiz'));
$table->align = array('left', 'left');
$table->size = array('', '');
$markscolumn = $displayoptions->marks >= question_display_options::MARK_AND_MAX;
if ($markscolumn) {
$table->head[] = get_string('marks', 'quiz');
$table->align[] = 'left';
$table->size[] = '';
}
$tablewidth = count($table->align);
$table->data = array();
// Get the summary info for each question.
$slots = $attemptobj->get_slots();
foreach ($slots as $slot) {
// Add a section headings if we need one here.
$heading = $attemptobj->get_heading_before_slot($slot);
if ($heading) {
$cell = new html_table_cell(format_string($heading));
$cell->header = true;
$cell->colspan = $tablewidth;
$table->data[] = array($cell);
$table->rowclasses[] = 'quizsummaryheading';
}
// Don't display information items.
if (!$attemptobj->is_real_question($slot)) {
continue;
}
// Real question, show it.
$flag = '';
if ($attemptobj->is_question_flagged($slot)) {
// Quiz has custom JS manipulating these image tags - so we can't use the pix_icon method here.
$flag = html_writer::empty_tag('img', array('src' => $this->image_url('i/flagged'),
'alt' => get_string('flagged', 'question'), 'class' => 'questionflag icon-post'));
}
if ($attemptobj->can_navigate_to($slot)) {
$row = array(html_writer::link($attemptobj->attempt_url($slot),
$attemptobj->get_question_number($slot) . $flag),
$attemptobj->get_question_status($slot, $displayoptions->correctness));
} else {
$row = array($attemptobj->get_question_number($slot) . $flag,
$attemptobj->get_question_status($slot, $displayoptions->correctness));
}
if ($markscolumn) {
$row[] = $attemptobj->get_question_mark($slot);
}
$table->data[] = $row;
$table->rowclasses[] = 'quizsummary' . $slot . ' ' . $attemptobj->get_question_state_class(
$slot, $displayoptions->correctness);
}
// Print the summary table.
$output = html_writer::table($table);
return $output;
}
Can anyone help me to change this code and show desired information in div format?
I could at last solve the problem but it may not be very professional:
* Create the summary page
*
* #param quiz_attempt $attemptobj
* #param mod_quiz_display_options $displayoptions
*/
public function summary_page($attemptobj, $displayoptions) {
$output = '';
$output .= $this->header();
$output .= $this->heading(format_string($attemptobj->get_quiz_name()));
$output .= $this->heading(get_string('summaryofattempt', 'quiz'), 3);
$output .= $this->summary_table($attemptobj, $displayoptions);
$output .= $this->summary_page_controls($attemptobj);
$output .= $this->footer();
return $output;
}
/**
* Generates the table of summarydata
* sara
* #param quiz_attempt $attemptobj
* #param mod_quiz_display_options $displayoptions
*/
public function summary_table($attemptobj, $displayoptions) {
// Prepare the summary table header.
$table = new html_table();
$table->attributes['class'] = 'generaltable quizsummaryofattempt boxaligncenter';
$table->head = array(get_string('question', 'quiz'), get_string('status', 'quiz'));
$table->align = array('left', 'left');
$table->size = array('', '');
$markscolumn = $displayoptions->marks >= question_display_options::MARK_AND_MAX;
if ($markscolumn) {
$table->head[] = get_string('marks', 'quiz');
$table->align[] = 'left';
$table->size[] = '';
}
$tablewidth = count($table->align);
$table->data = array();
// Get the summary info for each question.
$slots = $attemptobj->get_slots();
foreach ($slots as $slot) {
// Add a section headings if we need one here.
$heading = $attemptobj->get_heading_before_slot($slot);
if ($heading) {
$cell = new html_table_cell(format_string($heading));
$cell->header = true;
$cell->colspan = $tablewidth;
$table->data[] = array($cell);
$table->rowclasses[] = 'quizsummaryheading';
}
// Don't display information items.
if (!$attemptobj->is_real_question($slot)) {
continue;
}
// Real question, show it.
$flag = '';
if ($attemptobj->is_question_flagged($slot)) {
// Quiz has custom JS manipulating these image tags - so we can't use the pix_icon method here.
$flag = html_writer::empty_tag('img', array('src' => $this->image_url('i/flagged'),
'alt' => get_string('flagged', 'question'), 'class' => 'questionflag icon-post'));
}
if ($attemptobj->can_navigate_to($slot)) {
$row = array(html_writer::link($attemptobj->attempt_url($slot),
$attemptobj->get_question_number($slot) . $flag),
$attemptobj->get_question_status($slot, $displayoptions->correctness));
} else {
$row = array($attemptobj->get_question_number($slot) . $flag,
$attemptobj->get_question_status($slot, $displayoptions->correctness));
}
if ($markscolumn) {
$row[] = $attemptobj->get_question_mark($slot);
}
$table->data[] = $row;
$table->rowclasses[] = 'quizsummary' . $slot . ' ' . $attemptobj->get_question_state_class(
$slot, $displayoptions->correctness);
$counter=0;
foreach($row as $r)
{
if($counter ==0)
{
$output .= html_writer::start_tag('div', array('class' => 'qsummary'.' '.'questionNo' .' q'. $slot. ' '.$attemptobj->get_question_status($slot, $displayoptions->correctness)));
$output .= $r;
$output .= html_writer::end_tag('div');
$counter=1;
}
else{
if($counter ==1)
{
$output .= html_writer::start_tag('div', array('class' => 'qsummary' .' '.'questionStat'.' q'. $slot. ' '.$attemptobj->get_question_status($slot, $displayoptions->correctness)));
$output .= $r;
$output .= html_writer::end_tag('div');
$counter=1;
}
}
}
}
// Print the summary table.
// $output = html_writer::table($table);
return $output;
}

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.)

Styling Dynamically created selection drop box using HTML and CSS. How?

This code is in php file. How I will style tag with "Select Size" and customize the drop down section. Below is one div which i want to style but ht class is created dynamically. And here div drop box are created dynamically and the data entered is also been done dynamically. HELP
$i = 0;
$attribArr = array();
$sizeArr = array();
$colorArr = array();
$colorStr = "color";
$sizeStr = "size";
$phpArray = array(
0 => 001 - 1234567,
1 => 1234567,
2 => 12345678,
3 => 12345678,
4 => 12345678
);
foreach ($order['cart_items'] as $item) {
$i++;
$cssNo = $i % 5;
if ($cssNo == 0) {
$cssNo = 5;
}
$giftcss = "gift-info gift" . $cssNo;
// Get products description
$presult = array();
$productId = $item['product_id'];
$reslt = getProductOptions($productId);
$values = $reslt['values'];
info('option type=' . $reslt['type'] . ' Name=' . $reslt['name']);
$sizeOptionValues = '<option>';
$colorOptionValues = '<option>';
if ($reslt['name'] == 'Size') {
foreach ($values as $value) {
info('vl=' . $value['options_value_name']);
$sizeOptionValues.= str_replace(' ', '', $value['options_value_name']) . '</option><option>';
}
}
if ($reslt['name'] == 'Color') {
foreach ($values as $value) {
info('vl=' . $value['options_value_name']);
$colorOptionValues.= $value['options_value_name'] . '</option><option>';
}
}
$pquery = "SELECT products_description, pr.products_image, products_name FROM "
. TABLE_PRODUCTS_DESCRIPTION . " AS pd JOIN " . TABLE_PRODUCTS . " as pr ON pr.products_id = pd.products_id WHERE pd.products_id=" . $productId;
$presult = $db->Execute($pquery);
$product_name = $presult->fields['products_name'];
$product_image = $presult->fields['products_image'];
$product_desc = $presult->fields['products_description'];
$prodImgs = explode(".", $product_image);
$prodImg0 = $prodImgs[0];
$prodImgExt = $prodImgs[1];
$prod_img_name = $prodImg0 . 'v.' . $prodImgExt;
info("getOrder", "Product Name=" . $product_name . " prod image=" . $prod_img_name);
$prod_desc_url = EL_PROD_DESC_PATH . $productId;
$prodAttrQry = "SELECT * FROM " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " WHERE products_prid = " . $productId . " AND orders_id = " . $orderId;
$attrReslt = $db->Execute($prodAttrQry);
$color = false;
$colorValue = '';
$size = false;
$sizeValue = '';
$personalised = false;
$attr = false;
$personalisedMsg = '';
if ($attrReslt->RecordCount() > 0) {
$attr = true;
$attrArr = array();
while (!$attrReslt->EOF) {
$optName = $attrReslt->fields['products_options'];
$optValue = $attrReslt->fields['products_options_values'];
if ($optName == 'Size') {
$size = true;
$sizeValue = $optValue;
} else if ($optName == 'Color') {
$color = true;
$colorValue = $optValue;
} else if ($optName == '') {
$personalised = true;
$rslt = explode(".", $optValue);
if ((isset($rslt[1]) && $rslt[1] == 'jpg') || (isset($rslt[1]) && $rslt[1] == 'png')) {
$personalisedMsg = "<b>Uploaded Image</b> " . "<br><img style = 'width:200px; height:200px;'src = '$optValue'/>";
} else {
$personalisedMsg = '<b>Personal Message</b><br>' . $optValue;
}
}
$sizeArr[$i] = $sizeValue;
$colorArr[$i] = $colorValue;
$attribArr['personalise_val' . $i] = $personalisedMsg;
$attrReslt->MoveNext();
}
}
$colorVisibility = 'none';
$sizeVisibility = 'none';
$personalisedVisib = 'none';
$headlineVisib = 'none';
if ($color) {
$colorVisibility = 'inline';
$headlineVisib = 'inline';
}
if ($size) {
$sizeVisibility = 'inline';
$headlineVisib = 'inline';
}
if ($personalised) {
$personalisedVisib = 'inline';
}
$secondScreen .= <<
<div class="{$giftcss}">
<input type="hidden" name= "product_id{$i}" value="{$productId}"/>
<div class="gift-img"><img src="http://{$domainName}/gifts/images/{$prod_img_name}" height="250"></div>
<div class="divider"></div><div class="gift-desc"><h3>{$product_name}</h3><span>{$product_desc}</span></div>
<div style="width:100%;"><h3 style="display:{$headlineVisib}">Customize your gift</h3><br>
<p style="display:{$sizeVisibility};">Select Size<select id = "prod_size{$i}" name="prod_size{$i}" >{$sizeOptionValues}</select></p>
<p style="display:{$colorVisibility};">Select Color<select id = "prod_color{$i}" name="prod_color{$i}" >{$colorOptionValues}</select></p>
<p style="display:{$personalisedVisib};">{$personalisedMsg}</p></div>
MARKUP;
$secondScreen .= <<<MARKUP
Im not entirely sure what you mean? But if it's what I think you mean. To print out your php values into the class='' attribute you would:
<div class="<?php echo $giftcss; ?>">
<input type="hidden" name= "product_id<?php echo $i; ?>" value="{$productId}"/>
<div class="gift-img">
<img src="http://<?php echo $domainName; ?>/gifts/images/<?php echo $prod_img_name; ?>" height="250"></div>
Simply <?php echo $variable; ?> into each html attribute.

php report is very slow and crashes in firefox

I have a report that runs and returns 366 records, each containing a thumbnail that is 104 x 80 px. The issue is that the report runs very slowley even though I increased the memory size.
ini_set('memory_limit', '128M');
ini_set('max_execution_time','600');
After writing the SQL query I generate the table items here
generate_table_items($query_all_items);
This then runs through and checks for the image in the columns
function generate_table_items($query){
$columns = array();
$resultset = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$columncount = 0;
$rowcost = 0;
$rowsale = 0;
while ($row = mssql_fetch_assoc($query)) {
if (empty($columns)) {
$columns = array_keys($row);
echo '<tr><th scope="col" >'.implode('</th><th scope="col" >',get_column_name($columns)).'</th></tr>';
$columncount = sizeof(array_keys($row));
}
$resultset[] = $row;
echo '<tr><td>'.implode('</td><td>',report_image_check($row)).'</td></tr>';
if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$colspan = (count($columns)-2);
echo "<tr><th scope='row'>Documents</th><td colspan='$colspan' >";
$PKID = $row['ID'];
if($row['SumOfTotalCost'] || $row['SumOfSalePrice']){
$rowcost += $row['SumOfTotalCost'];
$rowsale += $row['SumOfSalePrice'];
$get_total = true;
}
$query_docs = mssql_query("select documents.* from dbo.documents where documents.Antiquities_id = $PKID") or die ('get docs query failed ' . mssql_get_last_message());
while($row_docs = mssql_fetch_assoc($query_docs)){
$document = "../documents/" . $row_docs['document'];
echo "<a href='$document' title='opens in a new window' target='_blank' >" . $row_docs['document'] . "</a> | ";
} // End while (list docs)
mssql_free_result($query_docs);
echo "</td></tr>";
myflush();
} // End if all items and all items by value report
} // End While
echo '<tr>';
for($i=0;$i < $columncount-4;$i++){
echo '<td> </td>';
}
echo '<td>Total Cost '. $rowcost.'</td>';
echo '<td>Total Sale '. $rowsale.'</td>';
echo '<td>Total Calculated Difference '. ($rowsale-$rowcost).'</td></tr>';
} // End function
function get_column_name($columns){
$newcol = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$thecount = 0;
foreach($columns as $col) {
if($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
// Don't list the PK
} else {
$newcol[] = '<img id="'.$col.'" src="../images/icons/arrow_down.png" alt="click to sort by" onclick="sortby(\''.$col.'\');" />' . $col;
}
$thecount++;
}
/*if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$newcol[] = "documents";
}*/
return $newcol;
}
function report_image_check($row){
global $base_url, $uploaded_images_folder;
$newrow = array();
$imageext = array();
$imageext[0] = ".jpg";
$imageext[1] = ".png";
$imageext[2] = ".gif";
$imageext[3] = ".tiff";
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$PKID = 0;
$thecount = 0;
foreach($row as $rn) {
if(in_array(strtolower(substr($rn,-4)),$imageext)){
$small_img_ext = substr($rn,-4);
$small_img = substr($rn,0,strripos($rn,"."));
$small_img = $small_img . '_140_105' . $small_img_ext;
$newrow[] = '<a href="' . $base_url . $uploaded_images_folder . '/' . $small_img . '" title="click to zoom on image" target="_blank" ><img src="' . $base_url . $uploaded_images_folder . '/' . $rn . '" alt="" width="50px" height="50px" /></a>';
} elseif($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$PKID = $rn;
} elseif($thecount == 2 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='../index.php?template=10&PKID=$PKID' target='_blank' >$PKID (click to view)</a>";
} else {
$newrow[] = $rn;
}
$thecount++;
myflush();
}
/*if (in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='#&PKID=$PKID' target='_blank' >Documents (click to view)</a>";
}*/
return $newrow;
} // End function
//// Flushing function
function myflush(){
ob_implicit_flush();
ignore_user_abort();
}
Can anyone see an issue with this code or see why it would take so long or why it crashes firefox? Would printing to pdf function work better?
It'll take a long time because you're nesting SQL queries... executing a second SQL query for every result that has been returned by the first query.... Doing a single query with a JOIN should help performance significantly.
Printing to PDF would almost certainly be slower: you'd eithe rneed a lot of code to position everything correctly in the report yourself, or to use one of the libraries that can take HTML and render it to a PDF (as you're already generating HTML anyway at the moment, this would be additional processing)

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:

Categories