Good evening.
This construction displays the values in a table that sorts them in alphabetical order.Those for example, if you click on the D link, only the names with letter D should be shown, and so on.
PHP code:
<?php
include ('engine/api/api.class.php');
$table = 'dle_post';
$fields = 'xfields';
$where = 'approve=1';
$multirow = 1;
$start = 0;
$limit = 0;
$xfield = 'actor';
$time = '14000';
$tr_new = 0;
$xfields = $dle_api->load_from_cache ($fields, $time, $xfields);
if( !$xfields ) {
$xfields = $dle_api->load_table ($table,$fields,$where,$multirow,$start,$limit);
$dle_api->save_to_cache ( xfields, $xfields);
}
$stack = array();
foreach($xfields as $value){
if($value[xfields]){
$row = xfieldsdataload($value[xfields]);
if($row[$xfield]){
$rowdata = explode( ",", $row[$xfield]);
foreach($rowdata as $value){
if($value){
$value = trim($value);
array_push($stack, $value);
asort($stack);
}
}
}
}
}
$stack = array_count_values($stack);
foreach($stack as $key => $count){
if($tr_new === 0){
echo '<tr class="new">';
}
echo "<td class='blok'>";
echo "<a href=/" . $xfield . "/";
echo $key;
echo " target='_blank' rel='noopener'>";
echo $key;
echo "</a>";
echo "<span>";
echo "(" . $count . ")";
echo "</span>";
echo "</td>";
$tr_new++;
if($tr_new === 1){
echo '</tr>';
$tr_new = 0;
}
}
JQuery:
$(function () {
var _alphabets = $('.alphabet > a');
var _contentRows = $('#countries-table tbody tr');
_alphabets.click(function () {
var _letter = $(this), _text = $(this).text(), _count = 0;
if(_text == 'all') _text = '.';
_alphabets.removeClass("active");
_letter.addClass("active");
_contentRows.hide();
_contentRows.each(function (i) {
var _cellText = $(this).children('td').eq(0).text();
if (RegExp('^' + _text).test(_cellText)) {
_count += 1;
$(this).fadeIn(400);
}
});
});
});
In page:
<div class="alphabet">
<a class="first" href="#">All</a>
A
B
C
...
<a class="last" href="#">Z</a></div>
<div id="conutries">
<table id="countries-table">
<tbody>
{include file="/code.php"}
</tbody>
</table>
</div>
</div>
Everything works fine, but I encounter such a problem - it turns out correctly to output only one value in one line tr ...
When I try to put a 4 td values to the tr line if($tr_new === 4) - they are not sort by alphabetically, they just displayed like this:
Whats wrong? What need to make this code work fine for me?
Thank you in advance for your help!
Related
I'm pulling an array from an external API, And I've got some help with usort on here, And It pushes it to the bottom, and empty values are on top. I tried using unset but that just emptied out my entire realArrival values.
e.g.
$fromThis = array(
"realArrival": "",
"realArrival": "Confirm. 06:18",
"realArrival": "Confirm. 06:19"
);
Into:
$intoThis = array(
"realArrival": "Confirm. 06:18",
"realArrival": "Confirm. 06:19",
"realArrival": ""
);
Here is my code on how I tried to do it. I'm sure you are shaking your head at this but here it goes.
$url = 'http://apis.is/flight?language=en&type=arrivals';
$json = file_get_contents($url);
$results = json_decode($json, TRUE);
$results = $results['results'];
function cmp($a, $b) {
return strcmp($a['realArrival'], $b['realArrival']);
}
//Sort Time
usort($results, "compare_time");
function compare_time($a,$b) {
$splitA= count(explode(' ',$a['realArrival']));
$splitB= count(explode(' ',$a['realArrival']));
if($splitA==2 && $splitB==2)
{
$first_time = strtotime(explode(' ',$a['realArrival'])[1]);
$second_time = strtotime(explode(' ',$b['realArrival'])[1]);
if($first_time==$second_time)
{
return strcmp($b['realArrival'], $a['realArrival']);
}
return ($second_time < $first_time) ? 1: 0;
}
return strcmp($a['realArrival'], $b['realArrival']);
}
echo '<table class="highlight bordered responsive-table grey darken-2 col s6">';
echo "<tr>";
echo '<th>Date</th>';
echo '<th>Flight Number</th>';
echo '<th>Airline</th>';
echo '<th>From</th>';
echo '<th>Schedule. Time</th>';
echo '<th>Status</th>';
echo "</tr>";
foreach ($results as $item => $val) {
echo "<tr>";
echo '<td>'.$val['date'].'</td>';
echo '<td>'.$val['flightNumber'].'</td>';
echo '<td>'.$val['airline'].'</td>';
echo '<td>'.$val['from'].'</td>';
echo '<td>'.$val['plannedArrival'].'</td>';
// HERE I TRIED TO TARGET THE EMPTY VALUES
if ($val === "") {
unset($results[$item]);
$results[] = $val;
echo '<td style="font-weight: bold;">'.$val['realArrival'].'</td>';
}
echo '</tr>';
}
I know this might seem clunky, but you could always just do something like...
$items_with_real_arrivals = array();
$items_without_real_arrivals = array();
foreach ($results as $item => $val) {
if ($item[‘realArrival’] === "") { $items_without_real_arrivals.push($item); }
else $items_with_real_arrivals.push($item);
}
$reordered_items = array();
for ($i=0; $i<count($items_with_real_arrivals); $i++) {
$reordered_items.push($item);
}
for ($i=0; $i<count($items_without_real_arrivals); $i++) {
$reordered_items.push($item);
}
foreach ($reordered_items as $item => $val) {
echo "<tr>";
echo ' <td>'.$val['date'].'</td>';
echo ' <td>'.$val['flightNumber'].'</td>';
echo ' <td>'.$val['airline'].'</td>';
echo ' <td>'.$val['from'].'</td>';
echo ' <td>'.$val['plannedArrival'].'</td>';
echo ' <td style="font-weight:bold;">' . $val['realArrival'].'</td>';
echo '</tr>';
}
I made a youtube list where I can click on texts that load youtube videos.
There is only one problem: When I play a video and click on another video link, the video I was playing doesn't stop. So I tried stopping it using jQuery, but no result.
So this is what my php generates:
function generateVideo() {
echo '<script type="text/javascript" src="scripts/video.js"></script>';
$tags = initTags();
$query = '
SELECT * FROM `youtube_links`';
$result = mysql_query($query);
if ( !$result) {
die('Error: '.mysql_error());
}
echo '<div id="content"><table>';
$i = 0;
$className = "";
while ($row = mysql_fetch_array($result)) {
$i++;
if ($i == 1) {
$className = "active";
} else {
$className = "inactive";
}
echo '
<tr>
<td>
<a class="'.$className.'" id="item_'.$i.'" onclick="switchVideo(this)">
'.$row['Title'].'
</a>
</td>
</tr>
';
}
echo '</table></div>';
$query = '
SELECT * FROM `youtube_links`';
$result = mysql_query($query);
if ( !$result) {
die('Error: '.mysql_error());
}
echo '<div id="videoPlayer">';
$i = 0;
$className = "";
while ($row = mysql_fetch_array($result)) {
$link = $row['Link'];
$i++;
if ($i == 1) {
$className = "activePlayer";
} else {
$className = "inactivePlayer";
}
echo '<iframe class="'.$className.'" id="ytplayer'.$i.'" type="text/html" width="640" height="390"
src="'.$link.'?version=3&enablejsapi=1"
frameborder="0">
</iframe>';
}
echo '</div>';
}
And this is my JavaScript:
function switchVideo(obj) {
var idText = obj.id;
var idArray = idText.split("_");
var id = idArray[1];
var videoPlayer = document.getElementById('ytplayer' + id);
var elements = document.getElementsByClassName("activePlayer");
for (var i = 0; i < elements.length; i++) {
elements[i].className = "inactivePlayer";
$(elements[i]).pause();
}
$('.inactivePlayer').each(function() {
$(this).stopVideo();
});
videoPlayer.className = "activePlayer";
}
You can see I added the youtube API to the iframes, so what is going wrong?
It might be a case of async loading of the javascript Youtube API.
Did you checked that?
Greetz, Alex
I got previousRow of record using this code
<?php
$previousRow = array();
while ($temp = mysql_fetch_row($res2))
{
echo "<br>currentRow:".$temp[1];
echo "previousRow:".$previousRow[1];
$previousRow = $temp;
}
?>
oupout
currentRow:1previousRow:
currentRow:5previousRow:1
currentRow:6previousRow:5
currentRow:7previousRow:6
currentRow:8previousRow:7
How can I check the value of the next row replaced by Previous Row ?
Any help would be grateful.
If I get you correctly, then something like this would help?
$previousRow = array();
$currentRow = mysql_fetch_row($res2);
while ($currentRow) {
$nextRow = mysql_fetch_row($res2);
echo "<br>currentRow:".$currentRow[1];
echo "previousRow:".$previousRow[1];
echo "nextRow:".$nextRow[1];
$previousRow = $currentRow;
$currentRow = $nextRow;
}
Please try code given below.
$res = array();
while ($result = mysql_fetch_row($r)) {
$res[] = $result;
}
echo "<pre>";
foreach($res AS $index=>$res1){
echo "Current".$res1[1];
echo " Next" . $res[$index+1][1];
echo " Prev" . $res[$index-1][1]; echo "<br>";
}
thanks
I'd collect all the rows first, then walk through them with a for:
<?php
$rows = array();
while ($temp = mysql_fetch_row($res2))
{
$rows[] = $temp;
}
$rowCount = count($rows);
for ($i = 0; $i < $rowCount; $i++) {
echo "<br>currentRow:".$rows[$i][1];
if ($i > 0) {
echo "previousRow:".$rows[$i - 1][1];
}
if ($i + 1 < $rowCount - 1) {
echo "nextRow:".$rows[$i + 1][1];
}
}
?>
I just learned about moustache.js and i am attempting to create an HTML template. However, the documentation is a bit hard to decipher. I found a good site that explains partials (which I believe I will need). I was hoping someone might be able to just 'get me started' on how I would need to do this.
I have a php file that I need to convert to the template:
PHP:
<div id='board'>
<?php
if ($threads)
{
$count = count($threads);
$perpage = 17;
$startlist = 3;
$numpages = ceil($count / $perpage);
if ($page == 'home') {$page = 1;}
$threadstart = ($page * $perpage) - $perpage;
$i = 0;
echo "<table class='board'>
<tr>
<th width='5%'><img src='".base_url()."img/board/icons/category_icon.png' alt='category_icon'/></th>
<th width='5%'>Tag</th>
<th width='50%'>Subject</th>
<th width='7.5%'>Author</th>
<th width='7.5%'>Replies/Views</th>
<th width='15%'>Last Post</th>
</tr>";
foreach ($threads as $list)
{ $i++;
$thread_owner = $this->thread_model->get_owner($list['owner_id']);
$thread_id = $list['thread_id'];
$query = $this->db->query("SELECT f.tag FROM filter_thread AS ft
INNER JOIN filter AS f ON ft.filter_id = f.filter_id
WHERE thread_id = $thread_id");
$result = $query->result_array();
$trunc_body = $this->thread_model->get_reply_summary($thread_id);
$filter = "";
$filter2 ="";
$ent = "entertainment";
foreach ($result as $string)
{
if ($string['tag'] == $ent) {
$filter2 .= "<div id='entertainment'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/entertainment_icon.png' title='Entertainment' alt='Entertainment'/>";
$filter2 .= "</p></div>";
} else {
$filter2 .= "<div id='misc'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/misc_icon.png' title='Misc' alt='Misc'/>";
$filter2 .= "</p></div>";
$filter .= " [".$string['tag']."]";
}
}
if (!$result) { $filter = "" AND $filter2 =""; }
if ($i > $threadstart AND $i <= $threadstart + $perpage)
{
echo "<tr>";
echo "<td>".$filter2."</td>";
echo "<td>".$filter."</td>";
echo "<td title='".$trunc_body['0']['body']."'>".ucfirst($list['subject'])."<div id='filter'><p></p></div></td>";
echo "<td><p>".$thread_owner."</p></td>";
echo "<td align='right'>Replies: ".$list['replies_num']."<br>Views: ".$list['views']."</td>";
$owner = $this->thread_model->get_owner($list['last_post_id']);
echo "<td>".$owner." <br>".$list['replystamp'] ."</td></tr>";
}
}
echo "</table>";
echo "<br>";
echo "Current Page: $page | ";
echo "Page: ";
for ($n = 1; $n < $numpages+1; $n++)
{
echo "<a href=".base_url()."main/home/$n>$n</a> | ";
}
}
?>
</div>
And here is the AJAX
$(function() {
$('#all').addClass('ui-selected')
$( "#selectable" ).selectable({
selected: updatefilters
});
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
url: 'updatefilters',
dataType: 'json',
data: { filters: filters },
success: function(data){
var template = "<div id ='board'>TESTING{{#body}}<table>";
var partials = "{{#subject}}";
//for (i=0 ; i< data.length ; i++)
//{html += "<tr><td>" + data[i].subject + "</td><td>" + data[i].body + "</td></tr>";}
//html += "</table></div>";
var html = Moustache.to.html(template, data, partials);
$('#board').html(html);
}
});
}
});
Im not sure how to navigate through the JSON array with moustache..and as it is, it does not update the page, though the commented out parts DO.
Thanks in advance!
First of all if you are receiving a json string you will need to to parse it (use $.parseJSON(data))
Once you have the data parsed you need to loop throught the JSON attributes.
For example:
If JSON has the following: body: {content: [dataObj:{data:'a'}, dataObj[data:'b']]}
do
<div>{{#body}}<div>
<div>{{#content}}<div>
<div>{{#dataObj}}<div>
<span>{{data}}<span>
If you are using partial, you will need to call them inside the main template.
Check the moustache5 documentation, it has improved a lot.
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: