I have a simple news system that i need to change so i can limit the items per page but i don't have anything that would do this, so i need to do this myself.
Basically the function just displays the whole array of the flat files and i would like to limit it to 3 items per page(configurable).
My starting logic was:
$itemspage=pages->current_page;
$itemsperpage=3;
$limitn=$itemperpage*$itemspage;
$itemindex=$limitn-2;
if page was 1 it would display the news from array index 1,2,3
if page was 2 it would display the news from array index 4,5,6
and so on...
i think this logically should work but what if the news in the array can't be split into 3? with this logic this should (at least on the starting index) cause a bug.
The whole code is here:
$list = $this->getNewsList();
$pages = new Paginator;
echo "<table class='newsList'>";
foreach ($list as $value) {
$newsData = file($this->newsDir.DIRECTORY_SEPARATOR.$value);
$newsTitle = $newsData[0];
$submitDate = $newsData[1];
unset ($newsData['0']);
unset ($newsData['1']);
$newsContent = "";
$itemspage=pages->current_page;
$itemperpage=3;
$limitn=$itemperpage*$itemspage;
$itemindex=$limitn - 2;
foreach ($newsData as $value) {
$newsContent .= $value;
}
echo "<tr><th align='left'>$newsTitle</th>
<th class='right'>$submitDate</th></tr>";
echo "<tr><td colspan='2'>".$newsContent."<br/></td></tr>";
}
echo "</table>";
The for hasn't been done yet only the logic behind the split. Could you help me?
I'm not sure how you're building your $newsContent, but maybe your answer is in here:
$list = $this->getNewsList();
$pages = new Paginator;
$itemspage = $pages->current_page;
$itemperpage = 3; // you might want te define this property in the paginator also ($itemperpage = $pages->items_per_page);
$currentPageList = array_slice($list, ($itemspage - 1) * $itemperpage, $itemspage);
echo "<table class='newsList'>";
foreach ($currentPageList as $value) {
$newsData = file($this->newsDir.DIRECTORY_SEPARATOR.$value);
$newsTitle = $newsData[0];
$submitDate = $newsData[1];
unset ($newsData['0']);
unset ($newsData['1']);
$newsContent = "";
$limitn=$itemperpage*$itemspage;
$itemindex=$limitn - 2;
foreach ($newsData as $value) {
$newsContent .= $value;
}
echo "<tr><th align='left'>$newsTitle</th>
<th class='right'>$submitDate</th></tr>";
echo "<tr><td colspan='2'>".$newsContent."<br/></td></tr>";
}
echo "</table>";
Notice the array_slice:
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
Related
I have this code to show how may times a champion was picked in a tournament for example ("Gragas : 2 Times" , "Syndra :4 times" , etc)
I'm using api from leaguepedia to recieve the informations
but im stucked right now, I'm having a problem when "echoing" my table to show the results.
So I want that "qtd" be by the "pick" side (Image1) and if there's an easy way to show what I want.
// $Result is a CURL coming from leaguepedia api
$result = json_decode($file_contents);
// Double foreach to access the values from leaguepedia api
foreach ($result as $d) {
foreach ($d as $data) {
// $data->title->Team1Picks is coming from league pedia api as a string separated by "," Ex:("Gragas,Shen,Maokai,etc")
// So I need to explode to an array to count.
$picks[] = explode(",", $data->title->Team1Picks);
}
}
// $mostpicked is an array for me to count how many times a champion was picked
// $f is an array to see the names of the picked champions
foreach ($picks as $pick) {
foreach ($pick as $total) {
$mostPicked[] = $total;
$f[] = $total;
}
}
// Basically here I'm counting how many times a champion was picked Ex : ("Gragas:2","Syndra:4" ,etc)
asort($mostPicked);
$mostPicked = array_count_values($mostPicked);
$name = array_unique($f);
asort($name);
// Foreach to get all unique names from the picks Ex : ("Gragas","Shen",etc) instead of ("Gragas , "Gragas" , etc)
foreach ($name as $champ) {
echo "<tr>";
echo "<td>" . $champ . "</td>";
echo "</tr>";
}
// This foreach to get the number of times a pick was made Ex : ("Gragas 2 Times")
foreach ($mostPicked as $pick) {
echo "<tr>";
echo "<td>" . $pick . "</td>";
echo "</tr>";
}
Here you go, this should do it.
// Hero name => pick count
$heroPicks = array();
foreach ($result as $d) {
foreach ($d as $data) {
//$data->title->Team1Picks is coming from league pedia api as a string separated by "," Ex:("Gragas,Shen,Maokai,etc")
// So i need to explode to an array to count.
$picks = explode(",", $data->title->Team1Picks);
foreach ($picks as $pick) {
$pick = trim($pick);
if (!array_key_exists($pick, $heroPicks)) {
$heroPicks[$pick] = 0;
}
$heroPicks[$pick] += 1;
}
}
}
uasort($heroPicks, function($a, $b) {
return $a - $b;
});
$heroPicks = array_reverse($heroPicks);
echo "Best picks:".PHP_EOL."<br />";
foreach ($heroPicks as $heroName => $pickCount) {
echo $heroName." - ".$pickCount.PHP_EOL."<br />";
}
It seems because you're putting the $pick in a new <tr>
Try adjusting your loops so that you're building an array of $champ=>$qtd then you an iterate over that and build your table as desired.
I want to pull rows from the database, attach a value to those rows, then order those rows based on a value. The problem is that in trying to do this via the while loop I get an error:
"Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in
C:\xampp\htdocs\productivitysuite\index.php on line 98"
My goal is to retrieve rows from a database and organize those rows based on a value I calculate in PHP php ($priority), then display certain values of those rows based on their priority. The problem is that I get this darn error and I don't know why, nor do I know where to look for help to resolve it! Hopefully SO can help diagnose this.
code:
<?php
$mysqli = mysqli_connect('127.0.0.1','root','', 'taskdb'); //open connection
//retrieve variables
$sql = "SELECT * FROM tasklist WHERE completion_flag = FALSE";
$sqldata = mysqli_query($mysqli,$sql) or die('error retrieving data');
//Display results
echo "<table>";
echo "<tr><th>Task</th><th>Type</th><th>Due Date</th>";
$counter = 0; //may need to make global, not sure
$results = array();
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
//store each row as variables
if ($row['externalFlag'] == 1) {
$E = 1;
} else{
$E = 0.5;
}
//days until completion
$nowDate = date("m/d/Y");
$D = 1 / (date_diff($row['dueDate']- $nowDate));
//Activity category multiplier
if($row['taskType'] == "Daily"){
$C = 0.5;
} elseif($row['taskType'] == "Maintenance"){
$C = 0.2;
} elseif ($row['taskType'] == "School_Study") {
$C = 0.75;
} elseif ($row['taskType'] == "Personal_Project") {
$C = 0.80;
} elseif ($row['taskType'] == "Work_Project") {
$C = 0.65;
}
$U = ($C - (1 / $D))* $E; //urgency rating; SET PER ROW!
$I = $row['importance']; //Importance rating
$priority = $U + $I;
$results[] = ($row => $priority);
//The array
$priorityOutput = $priorityRow.$counter;
++$counter;
echo "<tr><td>";
echo $row['taskName'];
echo "</td><td>";
echo $row['taskType'];
echo "</td><td>";
echo $row['dueDate'];
echo "</td></tr>";
//Make the below its own loop where I output in order of decreasing UI value
}
//now we have an array of key => value pairs with rows tied to a priority.
//We need to organize the rows by the priority
arsort($results);
echo "</table>"
$mysqli->close(); //close connection
?>
This is a syntax error with your subarray declaration.
Change
$results[] = ($row => $priority);
To
$results[] = array($row => $priority);
Correction: $row is an array, that cannot be used as a key.
I think you might mean:
$results[]=array($row['taskName']=>$priority);
Or maybe:
$results[]=array($priority=>$row);
Depending on your preferred structure.
As an aside, I would replace your taskType conditional block with a lookup array as a matter of clean / more compact code which I believe is easier to maintain and read.
Since i have many diffrent workers on my workkey and i just want to print every work once. I Though of doin a check like this.
At the end of the loop i wanna save the value from workkey. So before every print i will check, If the new workkey is diffrent from the last one = Dont print.
$counter = 0;
while(db2_fetch_row($queryexe)) {
$work = db2_result($queryexe, 'workkey');
$fname = db2_result($queryexe, 'fname');
$lname = db2_result($queryexe, 'lname');
if ($workkey != $saveworkkey){
$counter = 0;
}
if ($counter < 1){
print ( some stuff)
print ( some stuff)
print ( some stuff)
}
$workkey = $saveworkkey;
$counter++;
}
What I do to solve the issue is to add all values to an array with the key as array key. This way, even if there are duplicates they will overwrite eachother.
$workers = array()
while ($record = db2_fetch_row($queryexe)) {
$workers[$record['workkey']] = $record;
}
To print your values you can simply foreach
foreach ($workers as $worker) {
// print worker
}
i have data from php loop foreach like this
foreach ($query->result() as $row) {
echo $row->name;
}
how to make the result show only the end data without remove others if data has same (if data have same value, hide all except the last one) like this:
*sorry bad english, this is the first time i ask here. thank you
Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array();
foreach($query->result() as $row){
$pos = array_search($row->name, $arr);
if($pos !== false)
$arr[$pos] = '';
$arr[] = $row->name;
}
foreach($arr as $val){
echo $val.'<br/>';
}
Check this and let me know.
The data_seek method might help. This assumes your array is reasonable ordered to begin with.
$rowCount = 0;
$res = $query->result();
foreach($res as $row) {
if ($rowCount < $res->num_rows - 1) {
// set internal pointer to next row
$res->data_seek($rowCount + 1);
// if the row names match, print an empty string
// otherwise print the current name
$nextRow = $res->fetch_row();
if ($row->name == $nextRow->name) {
echo "";
// reset the internal pointer
$res->data_seek($rowCount);
} else {
echo $row->name;
}
} else {
echo $row->name;
}
// update the row count
$rowCount += 1;
}
$searchquery = mysql_query("SELECT * FROM regform_admin WHERE status = 'Approved' AND month LIKE '%".$checkmonth."%' AND day LIKE '%".$checkday."%' AND year LIKE '%".$checkyear."%' OR month2 LIKE '%".$checkmonth."%' AND day2 LIKE '%".$checkday."%' AND year2 LIKE '%".$checkyear."%' OR betday LIKE '%".$checkday."%'");
while($fetchres = mysql_fetch_array($searchquery)) {
$vehicles = $fetchres['vehicles'];
echo "<b>$vehicles</b><br>";
}
include "vehicledbconnect.php";
$searchquery2 = mysql_query("SELECT * FROM vehicletbl WHERE vehicle NOT LIKE '%".$vehicles."%'");
while($fetch = mysql_fetch_array($searchquery2)) {
$v = $fetch['vehicle'];
$vehed = $fetch['vehed']; $vehcap = $fetch['vehcap']; $vehyr = $fetch['vehyr'];
$type = $fetch['type'];
echo "<tr>";
echo "<td class=light><input type = 'checkbox' name='chk[]'></td>";
echo "<td class=light>$v</td>";
echo "<td class=light>$type</td>";
echo "<td class=light>$vehyr</td>";
echo "<td class=light>$vehed</td>";
echo "<td class=light>$vehcap</td>";
echo "<td class=light>$vehcolor</td>";
echo "</tr>";
echo "$array";
}
Is it possible to echo all values inside the while statement from $searchquery inside $searchquery2?
For example the values of $searchquery is:
vehicle1
vehicle2
vehicle3
Now I'm going to echo all of it inside $searchquery2, is it possible? I try to echo $vehicles (from $searchquery) inside $searchquery2 but it only echoes the last value (example. vehicle3) because I know it is not inside the while statement of $searchquery.
Is it possible? Thanks.
Build a loop in loop.
Try this:
mysql_query("SELECT * FROM regform_admin WHERE...")
while(...)
{
$vehicles = $fetchres['vehicles'];
echo "<b>$vehicles</b><br>";
mysql_query("SELECT * FROM vehicletbl WHERE vehicle NOT LIKE '%".$vehicles."%'");
while(...)
{
echo ...
}
}
Instead of echoing inside the while loop, try buffering the output to a variable instead:
$ob = '';
while($fetchres = mysql_fetch_array($searchquery))
$ob .= '<b>' . $fetchres['vehicles'] . '</b><br>';
echo($ob);
During your second while loop, $ob is still alive and you can echo it out just as easily. Here I'm storing it as a string, but you can store the values as an array also if you need more granular access to the elements.
Update
If you want to store them into an array, try it this way:
$ob = array();
while($fetchres = mysql_fetch_array($searchquery))
$ob[] = $fetchres['vehicle']; // This pushes the current vehicle onto the end of the array
After this loop, you just have the string for each vehicle in the array, and none of the formatting. You can add that in when you output the elements. Iterate over your array with foreach:
foreach($ob as $k => $v) {
// Inside this loop, $k is the key, or index, and $v is the value.
// You can change the names of these variables by modifying the line above, e.g.
// foreach($ob as $foo => $bar) <-- $foo = key/index, $bar = value
}