How can I format this code block so that every time this loop happens,
it moves each hyperlink element 20px from the left?
It's working at the moment but for the whole div not single items.
Example:
- LINK 1
-- LINK 2
--- LINK 3
Any help would be appreciated!
$linkArray = array();
$thisDir = '';
$baseDir = ($htmlRoot == '') ? '' : $htmlRoot;
for ($n=0; $n<count($dirArray); $n++) {
$thisDir .= $dirArray[$n].'/';
$thisIndex = MPBCDirIndex($htmlRoot.$thisDir);
$thisText = ($n == 0) ? $topLevelName : MPBCFixNames($dirArray[$n]);
$thisLink = ($thisIndex != '') ? '<span style="padding-left:20px;">'.$thisText.'</span>' : $thisText;
if ($thisLink != '') $linkArray[] = $thisLink;
}
$results = (count($linkArray) > 0) ? implode($separator, $linkArray) : '';
Well hmmm. You are already counting your iterations with the $n variable. SO:
EG.
for ($n=0; $n<count($dirArray); $n++) {
$pxvar = $n * 20;
$thisDir .= $dirArray[$n].'/';
$thisIndex = MPBCDirIndex($htmlRoot.$thisDir);
$thisText = ($n == 0) ? $topLevelName : MPBCFixNames($dirArray[$n]);
$thisLink = ($thisIndex != '') ? '<span style="padding-left:'.$pxvar.'px;">'.$thisText.'</span>' : $thisText;
if ($thisLink != '') $linkArray[] = $thisLink;
}
Note: the first iteration will have a padding of 0px. Not sure if thats how you want it?
Related
I am trying to automatically fill in a form with '0' if there is no value supplied. There are 14 questions to be filled in. The code I've written is ugly but works. I am looking to improve it by setting an array with all the questions and loop the command untill all the boxes are filled in with values or 0.
if ($q1 == '') {
$q1 = '0';
}
if ($q2 == '') {
$q2 = '0';
}
if ($q3 == '') {
$q3 = '0';
}
if ($q4 == '') {
$q4 = '0';
}
//... and so on up to $q14
if ($q13 == '') {
$q13 = '0';
}
if ($q14 == '') {
$q14 = '0';
}
Ideally, you should be using an array for these variables. Then you could simply loop through the indexes of the array to test and change as required. If you cannot change that, you can use variable variables to simplify the code:
for ($i = 1; $i <= 14; $i++) {
if (${"q$i"} == '') ${"q$i"} = 0;
}
If you do put the values in an array, you can loop through it with a foreach. Note the use of &$v to allow us to change the value in the loop:
foreach ($q as &$v) {
if ($v == '') $v = 0;
}
Demo on 3v4l.org
I have this array which contain around 1000 records. I want to display 20 array records per page.
$list=array(
array([title]=>"sony", [description]=>"camera"),
array([title]=>"sony", [description]=>"mobiles"),
array([title]=>"lenovo", [description]=>"laptop"),
array([title]=>"lenovo", [description]=>"mobiles")
);
I have used the following code for pagination. It is giving me a long row for pagination. Can someone help me to include previous and next code to my existing code so that my pagination will look good.
$page = isset($_REQUEST['page']) && $_REQUEST['page'] > 0 ? $_REQUEST['page'] : 1;
function display($list, $page = 1)
{
$start = ($page - 1) * 2;
$list = array_slice($list, $start, 15);
foreach ($list as $key => $val) {
echo $val['title'] . '<br/>';
echo $val['description'] . '<br/>';
echo "<br>";
}} $len = count($list);
$pages = ceil($len / 2);
if ($page > $pages or $page < 1)
{
echo 'page not found';
}
else
{
display($list, $page);
for ($i = 1 ; $i <= $pages ; $i++)
{
$current = ($i == $page) ? TRUE : FALSE;
if ($current) {
echo '<b>' . $i . '</b>';
}
else
{
?>
<?php echo $i;?>
<?php
}
}
}
Here's an example with the data array from your question.
The example
The page size is assumed to be 2 (20 in your question).
The size of the data array does not matter.
The start parameter is provided (as in your example) thru a GET parameter http://localhost/flipkart-api/fkt_offer.php?…start=index_or_page. This parameter is available in the script as $_GET['start'].
The previous and next start indices are to be calculated ($start +/- $maxpage, etc.).
To keep this example simple, I took the start index, not the page number, as parameter. But you also could use a page number and calculate the index, of course.
For the reason of brevity I omitted error checking ("what if no more items", etc.).
Code:
<?php
// The data array
$list=array(
array('title'=>"sony", 'description'=>"camera"),
array('title'=>"sony", 'description'=>"mobiles"),
array('title'=>"lenovo", 'description'=>"laptop"),
array('title'=>"lenovo", 'description'=>"mobiles")
);
// Evaluate URL
$proto = ((isset($_SERVER["HTTPS"])) && (strtoupper($_SERVER["HTTPS"]) == 'ON')) ? "https://" : "http://";
$hname = getenv("SERVER_NAME");
$port = getenv("SERVER_PORT");
if ( (($port==80)&&($proto=='http://')) || (($port==443)&&($proto=='https://')) ) { $port = ''; }
$params = '';
foreach ($_GET as $key=>$value) {
if (strtolower($key)=='start') continue;
$params .= (empty($params)) ? "$key=$value" : "&$key=$value";
}
$url = $proto . $hname . $port. $_SERVER['SCRIPT_NAME'] . '?' . $params;
// Page contents
$last = count($list)-1;
$start = (isset($_GET['start'])) ? intval($_GET['start']) : 0;
if ($start<0) $start = 0; if ($start > $last) $start = $last;
$maxpage = 2;
echo "<p>Start index = $start</p>" . PHP_EOL;
$curpage = 0;
for($xi=$start; $xi<=$last; $xi++) {
if ($curpage >= $maxpage) break;
$curpage++;
echo 'Entry ' . $curpage .
': ' . $list[$xi]['title'] .
' - ' . $list[$xi]['description'] .
'<br />' . PHP_EOL;
}
// Navigation
$prev = $start - $maxpage; if ($prev<0) $prev = 0;
$next = ( ($start+$maxpage) > $last) ? $start : $start + $maxpage;
$prev = ( ($start-$maxpage) < 0) ? 0 : $start - $maxpage;
echo '<p>Previous ';
echo 'Next</p>';
?>
Result (e.g)
Start index = 2
Entry 1: lenovo - laptop
Entry 2: lenovo - mobiles
Previous Next
I'm trying to fix something with which I'm not familiar with and don't know how to proceed. The forum on which I'm working is suppose to show under "TOP 50" only the most commented topics (2 pages by 25 topics) but it shows all topics (by 25) without any limitation of the pages. I need only the first 2 pages - but don't know how to get rid of the others?
I'm even not sure that the below code is the responsible one but please have a look and give me a hint if you see any solution.
This is the code:
{
public function __construct()
{
parent::__construct();
}
public function get_forum()
{
if ($_GET['l'] && ($_GET['l'] == 'leng' || $_GET['l'] == 'lrus' || $_GET['l'] == 'lde' || $_GET['l'] == 'ltr'))
$l = substr($_GET['l'], 1);
else
$l = 'eng';
(isset($_GET['num'])) ? $page = intval($_GET['num']) : $page = 1;
$id_user = intval($_SESSION['user_id']);
$lang = language::getLang();
if ($_GET['el']) {
switch ($_GET['el']) {
case 'categories':
return $this->getCategories($l);
break;
case 'top':
$top_lang = $_GET['ln'];
$c = $this->db->selectAssoc($this->db->Select('*', 'forum_categories ,forum_thems', "`forum_categories`.`lang` = '" . $l
. "' AND `forum_thems`.`id_categories` = `forum_categories`.`id`"));
$total_pages = count($c) / 25;
$p = "<div class=\"pageCounter_box\">Pages:";
if (empty($_GET['p'])) {
$_GET['p'] = 1;
}
for($i=1; $i<$total_pages+1; $i++){
if ($i == $_GET['p']) {
$class = 'class="active_page"';
}
$p .= "<a href=\"$top_lang/smoke/{$_GET['l']}/top?p=$i\" $class>$i</a>";
}
$p .= "</div>";
return $this->getTop($l) . $p;
break;
I think you could do a check in there of If ($total_pages > 2) { $total_pages = 2};
$c = $this->db->selectAssoc(
$this->db->Select('*', 'forum_categories ,forum_thems', "`forum_categories`.
`lang` = '" . $l. "' AND `forum_thems`.
`id_categories` = `forum_categories`.`id`"));
$total_pages = count($c) / 25;
if ($total_pages >2) { //limit to two pages
$total_pages = 2;
}
$p = "<div class=\"pageCounter_box\">Pages:";
if (empty($_GET['p'])) {
$_GET['p'] = 1;
}
"thanks a lot - great help! Do you further see why both pages might show active (page counter shows both active) when showing page 1? Page 2 is fine, there only Page 2 shows active..."
The $class variable is staying set, you need to have an else that sets the class to an empty string
for($i=1; $i<$total_pages+1; $i++){
if ($i == $_GET['p']) {
$class = 'class="active_page"';
} else {
$class = '';
}
$p .= "<a href=\"$top_lang/smoke/{$_GET['l']}/top?p=$i\" $class>$i</a>";
}
I'm trying to implement something like facebook's like widget which says something like:
You, Name1, Name2 and 20 other people like this
I fetched all my data to be able to display this HTML, but I can't seem to find the right algo to form the HTML string.
My main problem is that I don't know when to put the and string or the , (comma) string. If I just had to put names, it would work, but the problem is that the You string always has to be first.
I'm going to paste my code here and the output I'm getting for some special cases (it's PHP).
$current_user = 0;
$html = "";
$count = count($result);
$key = 0;
foreach($result as $liked){
if($key + 1 > $limit)
break;
if($liked->uid == $user->uid){
$current_user = 1;
continue;
}
$html .= "<a href='".$liked->href."'>".$liked->name."</a>";
if($key < $count - 2)
$html .= ", ";
elseif($key == $count - 2 && $key + 1 != $limit)
$html .= " and ";
$key++;
}
if($current_user){
$userHtml = "You";
if($count > 2)
$userHtml .= ", ";
elseif($count > 1)
$userHtml .= " and ";
$html = $userHtml.$html;
}
$html = "♥ by ".$html;
if($count > $limit){
$difference = $count - $limit;
$html .= " and ".$difference." ".format_plural($difference,"other","others");
}
return $html;
And in the special case where the current user is the last one to like this, it will show:
♥ by You, admin, edu2004eu and
Notice the and word doesn't have anything after it, because You should have been after it, but I put it at the beginning. Any help? I just need the logic, not the actual code.
You can try something like this:
$likedBy = array('admin', 'eduard', 'jeremy', 'someoneelse');
// check if I like it and if so move me to the front
if (in_array($currentUsername, $likedBy)) {
$me = array_search($currentUsername, $likedBy);
unset($likedBy[$me]);
array_unshift($likedBy, 'You');
}
// remove anything after the limit
$extra = array_splice($likedBy, 3);
// the comma list
$html = implode(', ', $likedBy);
// any extras? if so, add them here, if not rewrite the list so
// it's "You, Eduard and admin"
if (!empty($extra)) {
$html .= ' and '.count($extra);
} else {
$lastguy = array_splice($likedBy, 1);
$html = implode(', ', $likedBy).' and '.$lastguy;
}
$html .= ' like this';
Eduard,
You can fix this simply by putting $key++; at the top of the loop and taking out all the places where you have $key + 1 in the loop.
I think what's happening is that $key + 1 is assuming that there is a current user.
This line would also not display the current user if they are not in the first $limit number of entries
if($key + 1 > $limit)
break;
You can fix this by putting this after the code that looks for the current user.
In Java (I know, but its what I had running) it would look something like:
List<String> users = Arrays.asList("Brian","Tom","Jack","John");
int key = 0;
String html = "";
String currentUser = "Brian";
int limit = 3;
boolean foundCurrentUser = false;
for (String user : users) {
key ++;
if (currentUser == user) {
foundCurrentUser = true;
continue;
}
if (key > limit) {
continue;
}
html += user;
if (key < users.size() - 1) {
html += ",";
} else if (key == users.size() - 1 && key != limit) {
html += " and ";
}
}
if (foundCurrentUser) {
String userHTML = "You";
if (key > 2) {
userHTML += ", ";
} else if (key == 1) {
userHTML += " and ";
}
html = userHTML + html;
}
html = "Likeed by " + html;
if (users.size() > limit ) {
html += " and 3 other people";
}
System.out.println(html);
I need to generate random number of divs with five items per div (and remaining items in the last div) from random number of $totalItems and also not all the items satisfy $OKItems... Hopefully the code explains better than me.
My problem is that this script generates empty divs with no content in them.
<?php
$OKItems = 0;
$totalItems = rand(2,30);
for ($i = 0; $i < $totalItems; $i++) {
echo ($OKItems == 0 || $OKItems % 5 == 0) ? 'div open<br />' : '';
$testValue = rand(0, 1);
if ($testValue != 0) {
echo '1';
$OKItems++;
}
echo ($OKItems % 5 == 0 || $i+1 == $totalItems) ? '<br />div close<br />' : '';
}
?>
This is what I might get:
div open
div close
div open
11111
div close
div open
div close
div open
div close
div open
11
div close
And this is what I would have wanted in this case:
div open
11111
div close
div open
11
div close
<?php
const N = 5;
$totalItems = rand(2,30);
$items = array() ;
for ($i = 0; $i < $totalItems; $i++) {
$testValue = rand(0, 1);
if ($testValue != 0) {
$items[] = 1 ;
}
if( N == sizeof($items) || (($i == $totalItems - 1) && 0 < sizeof($items)) ) {
echo "<div>" . join(",", $items) . "</div>";
$items = array() ;
}
}
I think you need a bit more structure to your code.
My approach would be to break it up into several stages, as opposed to trying to do all the logic in the loop that outputs data.
What I'd suggest:
Decide how many items to be tested
Test each item and only copy the ones that pass into a new array
Partition this new array into sets of 5
Output each partition as a div
Code (untested):
// Decide how many items to test
$totalItems = rand(2,30);
// Test these items and add them to an accepted array
$items = Array();
for ($i = 0; $i < $totalItems; $i++) {
$testValue = rand(0, 1);
if ($testValue != 0) { $items[] = "1" }
}
//Partition them into sections
$partitions = array_chunk($items,5);
//Output as divs
foreach($partitions as $partition):
echo 'div open <br />';
foreach($partition as $item):
echo $item . "<br />";
endforeach;
echo 'div close <br />';
endforeach;
When you split up the code into logical steps, it becomes much easier to maintain and debug.
<?php
$OKItems = 0;
$totalItems = rand(2,30);
for ($i = 0; $i < $totalItems; $i++) {
echo ($OKItems == 0 || $OKItems % 5 == 0) ? 'div open<br>' : '';
$testValue = rand(0, 1);
if ($testValue != 0) {
echo '1';
$OKItems++;
}
if($OKItems % 5 == 0 || $i+1 == $totalItems) {
echo '<br>div close<br>';
$OKItems = 0;
}
}
?>
That should be working ;)
I changed your check line for an if function that also resets your $OKItems. The problem you had (i think) was that you got a 0 as the random value and that would keep $OKitems on 5.