I have three variables:
$title_order = 1;
$image_order = 2;
$content_order = 3;
and user can rearrange/reorder above variable, Like:
$title_order = 2;
$image_order = 1;
$content_order = 3;
Now, as per this variable I want to reorder below HTML
<h1><?php title() ?></h1>
<figure><?php thumbnail() ?></figure>
<details><?php thumbnail() ?></details>
how to show this as per variable number, like:
<figure><?php thumbnail() ?></figure> // show image 1st if $image_orer = 1;
<h1><?php title() ?></h1> // show h1 in 2nd if $title_order = 2;
<details><?php thumbnail() ?></details> // show h1 3rd if $content_order = 3;
please note user can set variable to anything between 1,2 and 3.
so please tell me how do i achieve this.
$result = '';
for ($i = 1; $i <= 3; ++$i) {
switch ($i) {
case $title_order:
$result .= '<h1>' . title() . '</h1>';
break;
case $image_order:
$result .= '<figure>' . thumbnail() . '</figure>';
break;
case $content_order:
$result .= '<details>' . thumbnail() . '</details>';
break;
}
}
echo $result;
Related
I'm working on a homework assignment while learning PHP for the first time. Everything is working, except for my switch statement. My professor is asking-
"Modify index.php
Get the selected value from the "calculate" radio button you created
Add a switch statement to set values for:
only the average calculation if the user selected the "average" radio button
only the total calculation if the user selected the "total" radio button
both the average and total if the user selected the "both" button."
I'd like to provide my entire index.php file in case it's important to see everything-
<?php
//set default values to be used when page first loads
$scores = array();
$scores[0] = 70;
$scores[1] = 80;
$scores[2] = 90;
$scores_string = '';
$score_total = 0;
$score_average = 0;
$max_rolls = 0;
$average_rolls = 0;
$score_total_f = '';
$score_average_f = '';
//take action based on variable in POST array
$action = filter_input(INPUT_POST, 'action');
switch ($action) {
case 'process_scores':
$scores = $_POST['scores'];
// validate the scores
$is_valid = true;
for ($i = 0; $i < count($scores); $i++) {
if (empty($scores[$i]) || !is_numeric($scores[$i])) {
$scores_string = 'You must enter three valid numbers for scores.';
$is_valid = false;
break;
}
}
if (!$is_valid) {
break;
}
// process the scores
$score_total = 0;
foreach ($scores as $s) {
$scores_string .= $s . '|';
$score_total += $s;
}
$scores_string = substr($scores_string, 0, strlen($scores_string)-1);
// calculate the average
$score_average = $score_total / count($scores);
// format the total and average
$score_total_f = number_format($score_total, 2);
$score_average_f = number_format($score_average, 2);
$calculate = filter_input(INPUT_POST, 'calculate');
switch($calculate) {
case "average":
$message_average = $score_average_f;
break;
case "total":
$message_total = $score_total_f;
break;
case "both":
$message_average = $score_average_f;
$message_total = $score_total_f;
break;
default: die("Invalid type");
}
break;
case 'process_rolls':
$number_to_roll = filter_input(INPUT_POST, 'number_to_roll',
FILTER_VALIDATE_INT);
$total = 0;
$max_rolls = -INF;
for ($count = 0; $count < 10000; $count++) {
$rolls = 1;
while (mt_rand(1, 6) != $number_to_roll) {
$rolls++;
}
$total += $rolls;
$max_rolls = max($rolls, $max_rolls);
}
$average_rolls = $total / $count;
break;
}
include 'loop_tester.php';
?>
Also, here is part of the other file where I had to create radio buttons-
<h3>What do you want to do?</h3>
<input type="radio" name="calculate" value="average" checked> Average<br>
<input type="radio" name="calculate" value="total"> Total<br>
<input type="radio" name="calculate" value="both"> Both<br>
<label>Scores:</label>
<span><?php echo htmlspecialchars($scores_string); ?></span><br>
<label>Score Total:</label>
<span><?php echo $message_total; ?></span><br>
<label>Average Score:</label>
<span><?php echo $message_average; ?></span><br>
</form>
Thank you!
Again, everything is working fine when I test in XAMPP, just not the switch statement. I get no output of any kind.
EDIT: Disregard my original answer, I tested out your original syntax and it seems to work fine. Sorry, that was a mistake on my part, though I'd still say the new code is more elegant.
There seems to be an issue with a misplaced break; - Here is a full working code for to 'process_scores' case:
case 'process_scores':
$scores = $_POST['scores'];
// validate the scores
$is_valid = true;
for ($i = 0; $i < count($scores); $i++) {
if (empty($scores[$i]) || !is_numeric($scores[$i])) {
$scores_string = 'You must enter three valid numbers for scores.';
$is_valid = false;
break;
}
}
if (!$is_valid) {
break;
}
// process the scores
$score_total = 0;
foreach ($scores as $s) {
$scores_string .= $s . '|';
$score_total += $s;
}
$scores_string = substr($scores_string, 0, strlen($scores_string)-1);
// calculate the average
$score_average = $score_total / count($scores);
// format the total and average
$score_total_f = number_format($score_total, 2);
$score_average_f = number_format($score_average, 2);
$calculate = filter_input(INPUT_POST, 'calculate');
$score_average_f = number_format($score_average, 2);
$score_total_f = number_format($score_total, 2);
switch($calculate) {
case "average":
echo "Average: " . $score_average_f;
break;
case "total":
echo "Total: " . $score_total_f;
break;
case "both":
echo "Average: " . $score_average_f . "<br />";
echo "Total: " . $score_total_f;
break;
default: die("Invalid type");
}
break;
I'm not sure about other the other part of your code, but I tested this and got the intended results. If you still see nothing, check what's in your $_POST variables. Also as a general advice for debugging: in a situation like this, just go through your code and echo stuff out inside and outside of every loop or function you believe your code should reach, to see where it gets derailed. It may not sound too professional, but it sure gets the job done.
I'm doing the same exercise. You need to define your variables before all the code runs.
$scores_string = '';
$score_total = 0;
$score_average = 0;
$max_rolls = 0;
$average_rolls = 0;
$message_average = 0;
$message_total = 0;
After I defined variables, $message_average and $message_total, everything worked fine.
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 am working on project which shows articles and this was done by article manager (a ready to use php script) but I have a problem, I want to show only four article titles and summaries from old list of article randomly which contains 10 article. Any idea how to achieve this process?
I have auto generated summary of article
<div class="a1">
<h3><a href={article_url}>{subject}</h3>
<p>{summary}<p></a>
</div>
When a new article is added the above code will generated and add into summary page. I want to add it to side of the main article page, where user can see only four article out of ten or more randomly.
<?php
$lines = file_get_contents('article_summary.html');
$input = array($lines);
$rand_keys = array_rand($input, 4);
echo $input[$rand_keys[0]] . "<br/>";
echo $input[$rand_keys[1]] . "<br/>";
echo $input[$rand_keys[2]] . "<br/>";
echo $input[$rand_keys[3]] . "<br/>";
?>
Thanks for your kindness.
Assuming I understood you correctly - a simple solution.
<?php
// Settings.
$articleSummariesLines = file('article_summary.html', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$showSummaries = 4;
// Check if given file is valid.
$validFile = ((count($articleSummariesLines) % 4 == 0) ? true : false);
if(!$validFile) {
die('Invalid file...');
}
// Count articles and check wether all those articles exist.
$countArticleSummaries = count($articleSummariesLines) / 4;
if($showSummaries > $countArticleSummaries) {
die('Can not display '. $showSummaries .' summaries. Only '. $countArticleSummaries .' available.');
}
// Generate random article indices.
$articleIndices = array();
while(true) {
if(count($articleIndices) < $showSummaries) {
$random = mt_rand(0, $countArticleSummaries - 1);
if(!in_array($random, $articleIndices)) {
$articleIndices[] = $random;
}
} else {
break;
}
}
// Display items.
for($i = 0; $i < $showSummaries; ++$i) {
$currentArticleId = $articleIndices[$i];
$content = '';
for($j = 0; $j < 4; ++$j) {
$content .= $articleSummariesLines[$currentArticleId * 4 + $j];
}
echo($content);
}
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>";
}
Can anyone help in this php page navigation script switch on counting normal serial number? In this script there is a var called "page_id" - I want this var to store the real page link by order like 0, 1, 2, 3, 4, 5 ...
<?
$onpage = 10; // on page
/*
$pagerecord - display records per page
$activepage - current page
$records - total records
$rad - display links near current page (2 left + 2 right + current page = total 5)
*/
function navigation($pagerecord, $activepage){
$records = 55;
$rad = 4;
if($records<=$pagerecord) return;
$imax = (int)($records/$pagerecord);
if ($records%$pagerecord>0)$imax=$imax+1;
if($activepage == ''){
$for_start=$imax;
$activepage = $imax-1;
}
$next = $activepage - 1; if ($next<0){$next=0;}
$end =0;
$prev = $activepage + 1; if ($prev>=$imax){$prev=$imax-1;}
$start= $imax;
if($activepage >= 0){
$for_start = $activepage + $rad + 1;
if($for_start<$rad*2+1)$for_start = $rad*2+1;
if($for_start>=$imax){ $for_start=$imax; }
}
if($activepage < $imax-1){
$str .= ' <<< End <span style="color:#CCCCCC">•</span> < Forward | ';
}
$meter = $rad*2+1; //$rad; ---------------------
for($i=$for_start-1; $i>-1; $i--){
$meter--;
//$line = '|'; if ($meter=='0'){ $line = ''; }
$line = ''; if ($i>0)$line = '|';
if($i<>$activepage){
$str .= " <a href='?page=".$i."&page_id=xxx'>".($i)."</a> ".$line." ";
} else {
$str .= " <strong>[".($i)."]</strong> ".$line." ";
}
if($meter=='0'){ break; }
}
if($activepage > 0){
$str .= " | <a href='?page=".$next."'>Back ></a> <span style='color:#CCCCCC'>•</span> <a href='?page=".($end)."'>Start >>></a> ";
}
return $str;
}
if(is_numeric($_GET["page"])) $page = $_GET["page"];
$navigation = navigation($onpage, $page); // detect navigation
echo $navigation;
?>
Instead xxx here (page_id=xxx) I want to link to real page number by normal order when this script show links but reversed.
Really need help with this stuff! Thanks in advance!
I were helped by one of the programmers with my above script. So here is a worked example of the reversed page navigation on PHP.
<?
$onpage = 10; // on page
/*
$pagerecord - display records per page
$activepage - current page
$records - total records
$rad - display links near current page (2 left + 2 right + current page = total 5)
*/
function navigation($pagerecord, $activepage){
$records = 126;
$rad = 4;
if($records<=$pagerecord) return;
$imax = (int)($records/$pagerecord);
if ($records%$pagerecord>0)$imax=$imax+1;
if($activepage == ''){
$for_start=$imax;
$activepage = $imax-1;
}
$next = $activepage - 1; if ($next<0){$next=0;}
$end =0;
$prev = $activepage + 1; if ($prev>=$imax){$prev=$imax-1;}
$start= $imax;
if($activepage >= 0){
$for_start = $activepage + $rad + 1;
if($for_start<$rad*2+1)$for_start = $rad*2+1;
if($for_start>=$imax){ $for_start=$imax; }
}
$meter = $rad*2+1; //$rad; ---------------------
$new_meter = $for_start-1;
if($activepage < $imax-1){
$str .= ' <<< End <span style="color:#CCCCCC">•</span> < Forward | ';
}
for($i=$for_start-1; $i>-1; $i--){
$meter--;
//$new_meter++;
//$line = '|'; if ($meter=='0'){ $line = ''; }
$line = ''; if ($i>0)$line = '|';
if($i<>$activepage){
$str .= " <a href='?page=".$i."&page_id=".($imax-$i-1)."'>".($i)."</a> ".$line." ";
} else {
$str .= " <strong>[".($i)."]</strong> ".$line." ";
}
if($meter=='0'){ break; }
}
if($activepage > 0){
$str .= " | <a href='?page=".$next."&page_id=".($imax-$next-1)."'>Back ></a> <span style='color:#CCCCCC'>•</span> <a href='?page=".($end)."&page_id=".($start-1)."'>Start >>></a> ";
}
return $str;
}
if(is_numeric($_GET["page"])) $page = $_GET["page"];
$navigation = navigation($onpage, $page); // detect navigation
echo $navigation;
?>
$page = keeps the page number from the reversed order
$page_id = keeps the real page by serial order. so you can make SELECT queries to database and ORDER BY id DESC use.