How can set different arrays that deals with different range of values? - php

I want to achieve the following html dynamically:
Time period AD:
<ul>
<li>1200</li>
<li>1300
<ul>
<li>1301</li>
</ul>
<li>
</ul>
Time period BC:
<ul>
<li>-200</li>
<li>-450
<ul>
<li>-451</li>
</ul>
</li>
</ul>
In the following I have set an array so that I can, by using some custom fields, push my dates into the array, then tell the whole code to calculate in 100 of years, in order to be able to place years like 1301 as a nested ul under 1300.
<ul>
<?php
$yearsArray = [];
$centuryHash = [];
query_posts(array(
'post_type' => 'post',
'posts_per_page' => -1
));
while ( have_posts() ) : the_post();
array_push($yearsArray, get_field("year"));
if (($wp_query->current_post +1) == ($wp_query->post_count)) {
$yearsArray = array_unique($yearsArray);
sort($yearsArray);
}
endwhile;
foreach ($yearsArray as $year) {
$currentCentury = floor($year/100)*100;
if(!$centuryHash[$currentCentury]){
$centuryHash[$currentCentury] = [];
}
if($currentCentury != $year){
$centuryHash[$currentCentury][] = $year;
}
}
foreach ($centuryHash as $century => $centuryYears) { ?>
<li class="dropdown">
<?php if($centuryYears){ ?>
<a class="btn btn-default" href="#" class="dropdown-toggle" data-date="<?php echo $century; ?>" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<?php echo $century; ?>
<span class='caret'></span>
</a>
<ul class='dropdown-menu'>
<?php foreach ($centuryYears as $year) { ?>
<li>
<a class="btn btn-default" data-date="<?php echo $year; ?>" href="#">
<?php echo $year; ?>
</a>
</li>
<?php }
echo "</ul>";
} else { ?>
<a class="btn btn-default" data-date="<?php echo $century; ?>" href="#">
<?php echo $century; ?>
</a>
<?php } ?>
</li>
<?php }
?>
</ul>
The problem that I can't figure out is how I can say like (verbal code):
If value is within the range of -450 till 2 then go into this array otherwise go in that array instead
From my end I could set in the cms (people will be able to insert content with dates) some flags so that I can do simple conditionals like (verbal code):
"Is this date from a or b? then do this or that"
But that creates an issue because I could flag a period of time and place the wrong date in the wrong period.
Therefore the last solution that I thought is to set a range of periods of times and delimiter some arrays by create different ones where I could dynamically push the values depending on their values.
This could be a start maybe (example from docs)? But how can I set an if to control what goes there or not?
foreach (range(0, 12) as $number) {
echo $number;
}

Here is a simple answer to your question.
If value is within the range of -450 till 2 then go into this array otherwise go in that array instead
if ($value >= -450 && $value <= 2) {
// do this
} else {
// do that
}
Hope, this answers to your question (which is, unfortunately, overloaded with dozens of code that doesn't apply to the question).

Related

Add to favorites functionality using Jquery in CodeIgniter framework

I am currently working on a tour website, where the number of destinations is available for the user. A Login user can like any destination which will be added to his favorites destination section. I have done this task successfully. But after liked the destination the like button appears multiple times or equal to the number of likes have the user done. Maybe I am wrong in my logic here is my code. The first loop is fetching all the destination and the second loop fetching the favorites destination.
Note:-Here I am showing only logic code not complete HTML or other PHP code
<?php foreach($listing_data as $list){ ?>
<?php foreach($favorites as $fav){ if($fav['link_id']==$list['id']){?>
<li class="pull-right"> <a class="Theme" id="liked"><i class="fas fa-heart"></i> </a> </li>
<?php } else {?>
<li class="pull-right"> <i class="far fa-heart"></i> </li>
<?php } } }?>
Just add a helper variable
and take out the html in 2th foreach.
$like = false; in each Site
Then in each site you loop $favorites, then walk in $favorites for check if TheSite is liked;
after second foreach you should compare if $like is true for use class "fas" or false for use class "far"
<?php foreach($listing_data as $list){
$like = false;
foreach($favorites as $fav){
if($fav['link_id']==$list['id']){
$like = true;
}
}
if($like){ ?>
<li class="pull-right">
<a class="Theme" id="liked"><i class="fas fa-heart"></i></a>
</li>
<?php } else { ?>
<li class="pull-right">
<i class="far fa-heart"></i>
</li>
<?php
}
}
?>
This is just a refactoring of the code to make it look a bit cleaner.
The links are not included as they are ? and also use id's that will not be unique.
So the code could become something like...
<?php foreach ($listing_data as $list): ?>
<?php
foreach ($favorites as $fav) {
$like = ($fav['link_id'] == $list['id']);
}
?>
<li class="pull-right">
<?php if ($like): ?>
<span>More Sensible Link 1</span>
<?php else: ?>
<span>More Sensible Link 2</span>
<?php endif; ?>
</li>
<?php endforeach; ?>

Change selected class to first instead of last date

I want my first date to be the selected one but as it is now the last one is the selected one, i've managed to get the years in the right order but the only problem im having now is getting the selected class on the first date instead of the ast one.
<div class="timeline">
<?php
$tl = unserialize($properties['timeline']);
$years = array();
foreach($tl as $t)
{
$e=explode("-", $t['date']);
$years[$e[2]][strtotime($t['date'])]=$t;
}
ksort($years);
?>
<div class="events-wrapper">
<div class="events">
<ol>
<?php
$i=1;
foreach($years as $y=>$t)
{
echo '<li><a href="#0" data-date="01/01/'.$y.'"'.($i==count($years)?' class="selected"':' class="older-event"').'>'.$y.'</a></li>';
$i++;
}
?>
</ol>
<span class="filling-line" aria-hidden="true"></span>
</div> <!-- .events -->
</div> <!-- .events-wrapper -->
Whats the best way to do this?
Just change your condition inside the foreach loop ($i==count($years) to ($i == 1).
foreach($years as $y=>$t){
echo '<li><a href="#0" data-date="01/01/'.$y.'"'.($i==1)?' class="selected"':' class="older-event"').'>'.$y.'</a></li>';
$i++;
}

How to create an if statement in PHP based on HTML values

I'm quite new to php, so be gentle.....
I have a basic list view that I have set up to match my html/css styles on a sidebar.....but every few listgroup items there are 'header' items on the list that do not inherit the same styles as other listgroup items.
For example, one list group item would have checkboxes and save icons where as the heading list group item would be the same size but would have bold text and no buttons.
This is what I have. On the section below the main one, I have the HTML values for a header list group item. Is it possible to tell the PHP to detect 'step-heading' as a class and then display the following code for all relevant values?
EDIT: I know that in the if-statement that $step-heading is invalid because I have not declared it as a variable...I simply have no idea what to put there otherwise.
<?php foreach ($tasks as $i => $task) { ?>
<li class="list-group-item" tabindex="-1">
<a class="listgroupwrap" href="#g<?= $i + 1 ?>">
</a>
<span class="step-number-container"> <?=$i + 1 ?>
</span>
<span class="btn-check">
<i class="glyphicon glyphicon-ok"></i>
</span>
<!--<span class="step-checkbox"></span>-->
<span class="step-name"><?php echo $task["name"] ?>
</span>
<span class="step-show-hide">
<span class="btn">
<i class="glyphicon glyphicon-chevron-right">
</i>
</span>
</span>
</li>
<?php } ?>
<?php
if ( $tasks == "step-heading" ) {
?>
<li class="list-group-item step-heading" tabindex="-1">
<span class="step-number-container">2</span>
<a class="listgroupwrap" href="#g<?= $i + 1 ?>">
</a>
<span class="step-name">Pre-meeting email, send below items:</span>
</li>
<?php;
}
?>
You can't have it both ways:
<?php foreach ($tasks as $i => $task) { ?>
^^^^^^---array
if ( $tasks == "step-heading" ) {
^^^^^^---array-as-string
An array in string context is simply the literal word Array.
Perhaps you mean:
if ( $task == "step-heading" ) {
^---no S
instead.

Using the same foreach multiple times

I'm currently working on a php script and stuck at this part. I have a database table which I want to display information from each row. I have two dropdown menus which I want to have the exact same names with just with a different url. I'm assuming this is possible, and I'm doing something wrong, as I'm not that advanced with php.
I found this question that was similar but didn't seem to see anything that helped much.
Use same foreach multiple times
Here is what I currently have
Top of page
<?php
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: login.php");
die("Redirecting to login.php");
}
$header = "SELECT id, location FROM table";
try
{
$headerstmt = $db->prepare($header);
$headerstmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
?>
Then here is the section with the foreach loops
<ul class="nav navbar-nav">
<li class="dropdown <?php if ($page == 'view') {echo 'active';} ?>">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">View <b class="caret"></b></a>
<ul class="dropdown-menu">
<?php foreach ($headerstmt->fetchAll() as $hrow) { ?>
<li><?php echo $hrow['location']; ?></li>
<?php } ?>
</ul>
</li>
<li class="dropdown <?php if ($page == 'edit') {echo 'active';} ?>">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Edit <b class="caret"></b></a>
<ul class="dropdown-menu">
<?php foreach ($headerstmt->fetchAll() as $hrow) { ?>
<li><?php echo $hrow['location']; ?></li>
<?php } ?>
</ul>
</li>
</ul>
The first foreach loop works correctly, however the second one is blank.
Thanks in advance if anyone is able help.
You should store the result of $headerstmt->fetchAll() in a variable and then use the resulting variable for the foreach loops.
$results = $headerstmt->fetchAll();
foreach( $results as $row ) {
}
foreach( $results as $row ) {
}
foreach( $results as $row ) {
}

Offset PHP array results

I am looking to offset a group of PHP array results to create multiple rows of data.
For example, the first row will contain the first four array results, with the second row displaying results 5-8 and the third row containing results 9-12.
Currently, I am printing out all 12 in one list, however I'd like a bit more display control (i.e. ordering the results into columns which I can style independent of each), hence why I'd like to offset the results.
My current PHP is below:
<?php
if (empty($tmdb_cast['cast'])) {
} else {?>
<section class="cast">
<p class="title">Cast</p>
<ul class="section_body"><?php
foreach($tmdb_cast['cast'] as $key => $castMember){
if ($key < 12) {?>
<li class="actor_instance clearfix"><?php
if ($castMember['profile_path'] != '') {?>
<img src="http://cf2.imgobject.com/t/p/w45<?php echo $castMember['profile_path']; ?>" class="actor_image pull-left" alt="<?php echo $castMember['name']; ?>" title="<?php echo $castMember['name']; ?>" /><?php
} else {?>
<img src="assets/images/castpic_unavailable.png" class="actor_image pull-left" alt="No image available" title="No image available" /><?php
}?>
<p class="actor"><?php echo $castMember['character']; ?> - <?php echo $castMember['name']; ?></p>
</li><?php
}
}?>
<div class="morecast pull-right">[...view all cast]</div>
</ul>
</section><?php
}?>
P.S. Apologies for how I've formatted the code in the above block - I'm still not 100% sure how to make it look "nice" on StackOverflow.
Use array_chunk to break a single dimension array into a 2D array. Then you can loop through each chunk, and then each result, to get that "offset" effect between them.
$chunks = array_chunk($tmdb_cast['cast'], 4); // 4 here, is the number you want each group to have
foreach($chunks as $key => $chunk)
{
foreach($chunk as $castMember)
{
//display castMember here
}
// add code between groups of 4 cast members here
}
First: mixing php and html this way is a very bad habbit... one day you will have to maintain your code and that day you will vomit all over your desk because you mixed different languages in one file...
That being said..
and without creating a new array:
foreach($tmdb_cast['cast'] as $key => $castMember)
{
if ($key < 12)
{
// your code goes here
// if key is 3, or 7 the code below will close the listcontainer and open a new one...
if( ($key+1)%4 == 0 AND $key <11)
echo '</ul> <ul class="section_body">';
}
}
Also replace this:
if (empty($tmdb_cast['cast']))
{
}
else {
with this:
if (!empty($tmdb_cast['cast']))
{
I'm not entirely sure what you're looking for but here's how I would format your code. Alternative syntax for 'if' is a little more readable, and the use of for loops instead of a foreach will give you the control over row numbers you say you're looking for.
<?php if( ! empty($tmdb_cast['cast'])): ?>
<section class="cast">
<p class="title">Cast</p>
<ul class="section_body">
<?php
for($i = 0; $i < 12; $i++):
$castMember = $tmdb_cast['cast'][$i];
?>
<li class="actor_instance clearfix">
<?php if($castMember['profile_path'] != ''): ?>
<img src="http://cf2.imgobject.com/t/p/w45<?php echo $castMember['profile_path']; ?>" class="actor_image pull-left" alt="<?php echo $castMember['name']; ?>" title="<?php echo $castMember['name']; ?>" />
<?php else: ?>
<img src="assets/images/castpic_unavailable.png" class="actor_image pull-left" alt="No image available" title="No image available" />
<?php endif; ?>
<p class="actor"><?php echo $castMember['character']; ?> - <?php echo $castMember['name']; ?></p>
</li>
<?php endfor; ?>
<div class="morecast pull-right">[...view all cast]</div>
</ul>
</section>
<?php endif; ?>

Categories