Show each date only once - php

All right, this must be an absolutely easy question, and I apologize for that.
I also apologize if I simply failed in finding the right search terms to use to come to an answer on my own. I did try, but my lack of fluency in PHP kind of makes me suck at searching.
I'm looking for a simple way to show each date only once within a foreach loop. I'm looping through data like so:
<?php
echo "<ul>";
foreach($rss_items as $i){
if($i->get_feed()->get_title() == 'Twitter (no # replies)'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Twitter</a>";
echo $i->get_title();
echo "</li>";
}
elseif($i->get_feed()->get_title() == 'Pinboard (jpcody)'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Pinboard</a>";
echo $i->get_title();
echo "</li>";
}
elseif($i->get_feed()->get_title() == 'Entries at Church Marketing Sucks by Joshua Cody'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Church Marketing Sucks</a>";
echo "<a href='" .$i->get_link()."'>" . $i->get_title() . "</a>";
echo $i->get_description();
echo "</li>";
}
elseif($i->get_feed()->get_title() == 'Flickr remove first paragraph'){
echo "<li>";
echo $i->get_date();
echo "<a href='" .$i->get_link()."'>Flickr</a>";
echo "<a href='" .$i->get_link()."'>" . $i->get_title() . "</a>";
echo $i->get_description();
echo "</li>";
}
}
echo "</ul>";
?>
And each item contains the date, so I'm getting the same date multiple times. I'd like to only have each date shown once, a la http://daringfireball.net.
I'm using CodeIgniter and the SimplePie library, so all of the data is being pulled directly instead of being stored in a db. I imagine a way to do it could be including a second if statement to check if the date has already been used, but I don't know how to execute this.
I'm pretty new to PHP, and I'm really looking to learn more than just have a solution given.
Any help you could give would be great!

You need to remember what was the date you used last, and print it only if it differs. You can try something like:
$previous_date = null;
foreach ($rss_items as $item) {
if ($item->get_date() != $previous_date) {
$previous_date = $item->get_date();
echo '<li>' . $previous_date . '</li>';
}
...
}
(And don't forget to HTML-encode the titles and links using htmlspecialchars.)

Do you mean you only want the date to be shown once, before the loop, or once per loop so that it looks like:
Date 1
- item 1
- item 2
- etc...
Date 2
- item 1
- item 2
- etc...
Could you clarify the format? Cause at the moment the date should be shown once for each $i that is valid.

Related

PHP create Url in mysqli_query while loop for every record

I would like to create a link within a while loop where the anchor link is a record from the query and the href passes a variable from the same query to another page so I only have to create one page that displays information based on the passed variable.
echo "<td>";
echo ''$row['result']''';
echo "</td></tr>";
This link kills my page and return an error.
echo "<td>";
echo ''.$row['result'].'';
echo "</td></tr>";
Should fix your code your quotes are not closed right
Your href string concatenation is incorrect.
It seems like you tried closing your strings and concatenating them halfway through and then stopped. Even with Stack Overflow you can see the string errors.
This is how your href echo should look:
echo '<a href="stats_game.php?idGame=' .$row['idGame'] . '>' . $row['result'] . '</a>';
It works fine for me
echo "<td><a href='stats_game.php?idGame=".$row['idGame']."'>".$row['result']."</a></td>";

Best way to combine PHP with HTML in CodeIgniter?

I've took over a PHP app which code is quite a mess so before making any major changes I've decided to rewrite it to MVC (CodeIgniter). As for pure html sections I use $this->load->view(file); technique, but I'm not sure how to cope with something like this:
echo "<tr>";
echo "<td class=\"border szczegolyTd\">";
echo "Kamp.: ".$kampania[$kamp]['idProject'];
echo "<br />";
echo "<b>".$kampania[$kamp]['name']."</b><br />";
echo "<div class='szczegolyDiv'><a class=\"pokaz szczegoly\" href=\"?pokaz=".$kampania[$kamp]['idProject']."\">";
echo "SZCZEGÓŁY";
echo "</a></div>";
if (isset($kampania[$kamp]['timestamp'][$iloLeftCustomers-1])) echo "<br />Dane od: <br /><b>".$kampania[$kamp]['timestamp'][$iloLeftCustomers-1]."</b>";
echo "<br />do: <br /><b>".$kampania[$kamp]['timestamp'][0]."</b>";
//echo "<br />".$ilOstatnichRozmow;
polacz();
$querySpr = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) AS ile FROM lista WHERE user=".$_SESSION['loginid']." AND kampania=".$kampania[$kamp]['idProject'].""));
rozlacz();
if ($querySpr['ile']==0) {
echo "<div id=\"".$kampania[$kamp]['idProject']."\" class=\"tabDodaj\">DODAJ DO OBSERWOWANYCH</div>";
}else{echo "<div class='komunikatMasz'>Masz tę kampanię na liście.</div>";}
echo "</td>";
I'm a beginner in CodeIgniter (and MVC in general), so I don't know all its features and which to choose. Perhaps it's not possible to seperate these 2 technologies completely - so it's more elegant to mainly use html and escape php scripts with <? ?> or to use php and echo html parts?
You can always write html in the template file and insert php in it to loop or echo.
echo "<tr>";
echo "<td class=\"border szczegolyTd\">";
echo "Kamp.: ".$kampania[$kamp]['idProject'];
echo "<br />";
Could be:
<tr>
<td class="border szczegolyTd">
Kamp.: <?php echo $kampania[$kamp]['idProject']; ?>
<br />
Putting code in those PHP tags wil actually fire the call in place. Mind you, to keep the html clean of bussines code make sure you only use echo, foreach, for or if in it.
In CodeIgniter you could render a view file and insert into a "partial" view and just echo it in the main template using TRUE for the 3rd parameter. This only buffers the output instead if immediatly outputting it.
$data['content'] = $this->load->view('ding/templatefile',$vars,TRUE);
if you are really new, please follow this tutorial its nice && informative.
yes it is possible, the best use is short tag + equal sign <strong><?=$variable?></strong> and it echoes whatever is in $variable, whenever you use foreach() use either
foreach($elements as $element) {
$string = "";
$string .= "new line" . $element->id . "<br>";
$string .= "line 2" . $element->name;
echo $string;
}
or just echo lines as you wish
foreach($elements as $element) {
echo "new line" . $element->id . "<br>";
echo "line 2" . $element->name;
}
but remember, before going in to foreach loop, please check if you have valid $variable to go thru. (empty(), isset(), $variable != FALSE...)
note:
if you need condition while echoing basic text use
<strong><?=(condition) ? 'TRUE' : 'FALSE' ?></strong>
example
<strong><?=(isset($variable)) ? $variable : '' ?></strong>
I would advise you go read up on the flow of how a MVC works, but this should point you in the right direction.
In the controller you instantiate the model of the data like:
$this->load->model("lista");
Then,
$data = $this->lista->getCountList($_SESSION['loginid'], $kampania[$kamp]['idProject']);
where in the lista model you have the function:
getCountLista($loginId, $projectId)
which does this part:
return mysql_fetch_assoc(mysql_query("SELECT COUNT(*) AS ile FROM lista WHERE user=".$loginId." AND kampania=".$projectId.""));
Then you pass the returned data to the view
$this->load->view(file, array("listData" => $data));
and in the view:
$listaData[$kamp]['idProject']
It creates an variable in the view foreach item in the array passed in the view.
I commend you to read documentation about MVC.

php limit what happens in 'while' loop

I have some code that creates a divs for each result of a query. My problem is that, I only want the same amount of divs created for the result set I'm limiting.
For example, this query produces about 8-9 rows however, in this case, if $busroute==2, and there are only 2 results that match this, I only want to to create 2 divs and close them. Right now, as I have it, it's creating a div - /div set for each iteration of the "while" loop.
<?php
mysql_data_seek( $result,0);
while ($i2=mysql_fetch_array($result)) {
$busnumber=$i2['NAME'];
$busroute=$i2['route'];
$busdirection=$i2['direction'];
$timediff=$i2['TimeDiff'];
$timestamp=$i2['TIMESTAMP'];
if ($busroute=='2'){
echo "<div class='businfo'>";
echo "<p>Bus #: ".$busnumber."<br>Direction: ".$busdirection."<br>Bus Route : ".$busroute."<br>";
echo "Timestamp : $timestamp</p>";
}
echo "</div>";
}
?>
So, if $busroute==2, and there are two results where $busroute==2, then the following should only output twice.
echo "<div class='businfo'>";
echo "<p>Bus #: ".$busnumber."<br>Direction: ".$busdirection."<br>Bus Route : ".$busroute."<br>";
echo "Timestamp : $timestamp</p>";
}
echo "</div>";
Thanks in advance for any help.
d -
Your code already looks OK for what you want.
I think "</div>" should be inside your IF.
Replace
if ($busroute=='2'){
echo "<div class='businfo'>";
echo "<p>Bus #: ".$busnumber."<br>Direction: ".$busdirection."<br>Bus Route : ".$busroute."<br>";
echo "Timestamp : $timestamp</p>";
}
echo "</div>";
with
if ($busroute=='2'){
echo "<div class='businfo'>";
echo "<p>Bus #: ".$busnumber."<br>Direction: ".$busdirection."<br>Bus Route : ".$busroute."<br>";
echo "Timestamp : $timestamp</p>";
echo "</div>";
}

Using xml attribute id in page url and on page

Im pulling in data about sports events via an xml feed, im using simplexml to do so. So far ive got a foreach loop that loops through all of the events and echos them out as a list of event names wrapped in <a> tags, pointing to a page event.php?=id (id is determined via the events attribute called id).
to do this im using
<?php
$xml = simplexml_load_file("openbet_cdn.xml");
foreach($xml->response->williamhill->class->type->market as $market) {
$market_attributes = $market->attributes();
printf("%s\n",
$market_attributes->id,
$market_attributes->name);
}
?>
the feed I'm using is http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N
What im having trouble with is on my page event.php i keep getting the first event in the xml feed displayed. To do this im using :
<?php
foreach ($xml->response->williamhill->class->type->market->participant as $participant) {
$participant_attributes = $participant->attributes();
echo "<tr>";
// EVENT NAME
echo "<td>";
echo "<a href=".$market_attributes['url'].">";
echo $participant_attributes['name'];//participants name
echo "</a>";
echo"</td>";
//ODDS
echo "<td>";
echo $participant_attributes['odds'];
echo "</td>";
echo "</tr>";
}
?>
I can see why it is because im not referencing the id which is in the URL of the event page. But I'm not quite sure of how to do this, any idea how I can tackle this ?
You just need to add an if within the loop so that you only target the event ID that matches the one in the querystring. A nested loop is also needed because you want to loop over each market to find the matching id, then loop over each of its participants.
foreach ($xml->response->williamhill->class->type->market as $market) {
if($market->attributes()->id == $_GET['id']) {
foreach($market->participant as $participant) {
$participant_attributes = $participant->attributes();
echo "<tr>";
// EVENT NAME
echo "<td>";
echo "<a href=".$market->attributes()->url.">";
echo $participant_attributes['name'];//participants name
echo "</a>";
echo"</td>";
//ODDS
echo "<td>";
echo $participant_attributes['odds'];
echo "</td>";
echo "</tr>";
}
break; // <-- we've found the target and echo'ed it so no need to keep looping
}
}

Create page navigation using php

I am having some issues trying to create page navigation using php,
I have variable called $PageNo that I can navigate through using using next prev links -1 or +1.
eg.
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo+1)."'>Next</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo-1)."'>Prev</a>";
but aswell as this is want to display direct links to the pages so i have a navigation like so
PREV 1 2 3 4 NEXT
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo+1)."'>Next</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=1'>1</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=2'>2</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=3'>3</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=4'>4</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo-1)."'>Prev</a>";
If I know the total number of product pages is 4 how would you generate the links to give
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=1'>1</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=2'>2</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=3'>3</a>";
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=4'>4</a>";
Any help would be great.
How about to try this one?
// $total_num : total number of the pages
foreach (range(1, $total_num) as $p) {
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=$p"'>$p</a>";
}
You need to do the math, and then a little bit of code.
calculate the number os pages you need (based on the number os records and records per page)
Just use a for loop to do links like (not tested):
for ($page = 1; $page <= $total_pg; ++$page) {
echo "$page";
}
then, the product.php page reads that number and displays the subset of records
This is a simple for loop, and it's very basic stuff that's in all programming languages out there (just like if/else statements and while loops among others).
Say the total number of pages is 4, then you set a random variable, say $p (for pages) initially to it's start value 1, then continue the loop, increasing $p by 1 every time until $p is 4. Would result in this:
// Previous link before the numbers (unless we are on page 1)
if($PageNo > 1) {
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo-1)."'>Prev</a>";
}
// We loop over all the numbered pages here
for($p = 1;$p <= 4;$p++) {
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=" . $p . "'>" . $p . "</a>";
}
// Next link goes after the numbers (if there are any pages left)
if(($PageNo + 1) <= $p) {
echo "<a href='http://".$_SERVER["HTTP_HOST"]."/product.php?page=".($PageNo+1)."'>Next</a>";
}

Categories