PHP variable array + loop - php

I should say first of all I'm not a PHP guy, so if anyone can help with this, I'll do my best to understand any suggestions.
I have the following code that accesses an API and outputs some of the data, via PHP wrapper:
$idMovie=11;
$pelinfo = $tmdb_V3->movieDetail($idMovie);
<h1><?php echo $pelinfo[original_title]; ?></h1>
<h2><?php echo $pelinfo[release_date]; ?></h2>
<img src="<?php echo $pelinfo[poster_path]; ?>">
<p><?php echo $pelinfo[overview]; ?></p>
This works fine, it shows the data for one item. What I need to do though is show the data for many more items. So far I've just repeated the block and changed the $idMovie variable - but this is of course, is not the way to do it.
I think I need to do this:
Set up an array to hold each variable, so $idMovie[12,34,56,78]
Create a loop to go through each variable, and output the data using
my code block above.
If anyone can point me in the right right direction, that would be most helpful.
Thanks
Dave

There's one very useful construct in PHP - foreach:
<?php foreach($idMovies as $idMovie):
$pelinfo = $tmdb_V3->movieDetail($idMovie); ?>
<h1><?php echo $pelinfo['original_title']; ?></h1>
<h2><?php echo $pelinfo['release_date']; ?></h2>
<img src="<?php echo $pelinfo['poster_path']; ?>">
<p><?php echo $pelinfo['overview']; ?></p>
<?php endforeach; ?>
Here I've used so-called 'alternative syntax', useful when PHP snippets are included in HTML template.
Yet, there's more than one way to iterate through this array. For example:
<?php
$idMovies = array(11, 22, 33, 42);
$pelHTMLs = array_map(function($id) use ($tmdv_V3) {
$pelInfo = $tmdv_V3->movieDetail($id);
// perhaps you should check the result here, no?
return <<<HTML
<h1>$pelInfo[original_title]</h1>
<h2>$pelInfo[release_date]</h2>
<img src="$pelInfo[poster_path]" />
<p>$pelInfo[overview]</p>
HTML;
}, $idMovies);
echo implode("\n", $pelHTMLs);
?>
Here I used array_map function to create an array $pelHTMLs, each element of which is some HTML representation of a movie data, related to an id taken from $idMovies array. Then all these parts are just 'joined' into a single string with 'implode' function - and echoed out.
This form is quite often used in PHP 5.3+ environments (when you can supply an anonymous function into array_map and similar list comprehension functions). But it actually can be done in PHP 5.2 too - you just need to extract this part into a separate function (or class method), then give its name (or array with two params - class name and method name) as 'callback' argument.

$idMovie = array(12,34,56,78);
foreach($idMovie as $id){
$pelinfo = $tmdb_V3->movieDetail($id);
echo "<h1> $pelinfo[original_title] </h1>
<h2> $pelinfo[release_date] </h2>
<img src='$pelinfo[poster_path]'>
<p>$pelinfo[overview]</p>";
}

Try using
while($data = $pelinfo){<h1><?php echo $pelinfo[original_title]; ?></h1>
<h2><?php echo $pelinfo[release_date]; ?></h2>
<img src="<?php echo $pelinfo[poster_path]; ?>">
<p><?php echo $pelinfo[overview]; ?></p>}
This should go through all of it.
From here you should be able to work out your girst question.

Its as simple as your pseudo-code. Here as an implementation:
<?php
$ids = array('12','34','56','78') //array of movie ids
$foreach($ids as $id) : //I'm a huge fan of foreach vs for
$pelinfo = $tmdb_V3->movieDetail($id);
?>
<h1><?php echo $pelinfo[original_title]; ?></h1>
<h2><?php echo $pelinfo[release_date]; ?></h2>
<img src="<?php echo $pelinfo[poster_path]; ?>">
<p><?php echo $pelinfo[overview]; ?></p>
<?php endforeach; ?>

$idMovieArr=array(11,22,35,...);
foreach ($idMovieArr as $key) {
$idMovie=$idMovieArr[$key];
$pelinfo = $tmdb_V3->movieDetail($idMovie);
<h1><?php echo $pelinfo[original_title]; ?></h1>
<h2><?php echo $pelinfo[release_date]; ?></h2>
<img src="<?php echo $pelinfo[poster_path]; ?>">
<p><?php echo $pelinfo[overview]; ?></p>
<?php } ?>
something like this

Related

Echo 2 SQL ROW Value in PHP

Sorry I'm just beginner in PHP MYSQLi.
I want to ask if how to call 2 sql row value here is my code
<h2><?php echo $userRow['agentFname']; ?></h2>
I want to add 'agentLname' beside 'agentFname'
Thank you.
Option 1...
<h2><?php echo $userRow['agentFname'].' '.$userRow['agentLname'] ?></h2>
Option 2...
<h2><?php echo $userRow['agentFname'] ?> <?php echo $userRow['agentLname'] ?></h2>
Then just print it:
<h2>
<?php
echo $userRow['agentFname'];
echo " ";
echo $userRow['agentLname'];
?>
</h2>
Try this
<h2><?php echo $userRow['agentFname'].' '.$userRow['agentLname']; ?></h2>

Kirby CMS - add an image modified timestamp

I'm learning Kirby CMS.
I have a page displaying a series of images, I'm unsure how to get the date the image was uploaded.
I think it is something to do with the $file variable?:
$file->modified($format=false)
the last modified timestamp
here is my php loop:
<?php if($page->hasImages()): ?>
<ul class="gallery">
<?php foreach($page->images() as $image): ?>
<div class="gallerySegment">
<h3 class="guidelineHead"><?php echo $image->title() ?></h3>
<p><?php echo $image->caption() ?></p>
<li><img src="<?php echo $image->url() ?>" width="<?php echo $image->width() ?>" height="<?php echo $image->height() ?>" alt="<?php echo $image->title() ?>" /></li>
</div>
<?php endforeach ?>
</ul>
<?php endif ?>
I think this isn't possible by default in kirby 1. You could use the php-function filetime().
In case of Kirby 2 you can write $file->modified($format = false) as in your proposal.
You should be able to simply do something like this within your loop.
<p>Uploaded at: <?php echo $image->modified('d. F Y'); ?></p>
This is available in Kirby 1 as well as in Kirby 2 as a single "image object" you have in your $image variable is always an extended "file object". That means you can use all file object methods on image objects as well.
If you need any information about how set the $format ('d. F Y'), you should have a look at PHPs date() function explanation

Cleaner code when using alternative syntax and associative arrays.

Im writing a foreach loop for my view using the alternative syntax, to get a piece of html like this
<h3>My Post</h3>
Ive used the line below, but it seems awfully clunky with all the concatenation.
<?php
foreach ($index_posts as $post):
?>
<h3><?= "" . $post['title'] . ""; ?></h3>
<?php
endforeach;
?>
Ive also tried writing it like this :
<?= "<a href='post.php/?id=$post['id']'>$post['title']</a>"; ?>
But it shows errors when written in sublime text 2 around the ['id'] and ['title'] any ideas why this is, as they are single quotes ?
Is there another way i could write this that is cleaner ?
You could just do:
<?php foreach ($index_posts as $post): ?>
<h3>
<a href="post.php?id=<?php echo $post['id']; ?>">
<?php echo $post['title']; ?>
</a>
</h3>
<?php endforeach; ?>
The reason Sublime is showing an error when you do this
<?= "<a href='post.php/?id=$post['id']'>$post['title']</a>"; ?>
is due to the fact that it's a syntax error as you can't have complex variables (like array values with strings for keys) interpolated into a string directly like this. You need to wrap them in {}
<?= "<a href='post.php/?id={$post['id']}'>{$post['title']}</a>"; ?>
Alternatively, you could use:
foreach ($posts as $post) {
printf('%s', $post['id'], $post['title']);
}
<?php foreach ($index_posts as $post): ?>
<h3>
<a href='post.php/?id=<?=$post['id']?>'>
<?=$post['title']?>
</a>
</h3>
<?php endforeach; ?>
Keeping it to HTML whenever you can; I much prefer to not 'echo' out HTML unless needed, although this question really quite about preference. Afterall, PHP is an templating language!
Gotta help a fellow sam...
<?php echo "<h3>{$post['title']}</h3>"; ?>

Filtering out items using SimpleXML

Been looking around and am stumped. Basically I'm trying to filter out a result from an xml feed and hide it from displaying in the html output. I'm trying to find out the venue "Hornblower Cruises and Events" and if it exists, hide the whole , which is the parent of all the nodes.
Here's the URL: http://www.sandiegomagazine.com/goldstartest/rss3-exclude.php
Here's my code:
<?php
$myfeed = simplexml_load_file('https://www.goldstar.com/api/listings.xml?api_key=6d0d598c69dfecfcf028b0d2b3c9b693b606ad8c&postal_code=92101');
$i = 0;
foreach ($myfeed as $goldstar):
$title=$goldstar->headline_as_html;
$summary=$goldstar->summary_as_html;
$dates=$goldstar->upcoming_dates->event_date->date;
$ourprice=$goldstar->our_price_range;
$fullprice=$goldstar->full_price_range;
$img=$goldstar->image;
$link=$goldstar->link;
$venue_name=$goldstar->venue->name;
$venue_street=$goldstar->venue->address->street_address;
$venue_locality=$goldstar->venue->address->locality;
$venue_region=$goldstar->venue->address->region;
$venue_zip=$goldstar->venue->address->postal_code;
$venue_phone=$goldstar->venue->phone;
$category=$goldstar->category_list->category->name;
// if ($venue_name == 'Hornblower Cruises and Events'){
// unset($myfeed->event);
//echo $myfeed->asxml();
//}
if (++$i > 20) {
// stop after 10 loops
break;
}
?>
<html>
<head></head>
<body>
<div class="gs-item">
<div class="gs-itemcontent">
<h3 class="gs-cat"><?php echo $category; ?></h3>
<h2><?php echo $title; ?></h2>
<h4 class="gs-date">Date: <?php echo $dates; ?> <br/>For more show dates, click here</h4>
<img src="<?php echo $img; ?>" />
<p><?php echo $summary; ?></p>
<div id="gs-callout">
<span class="fullprice">Full Price: <?php echo $fullprice; ?></span>
<br/>
<span class="ourprice">Our Price: <span class="gs-hilite"><?php echo $ourprice; ?></span></span>
<p><a class="gs-button" href="<?php echo $link; ?>" target="_blank">Buy Tickets ยป</a></p>
</div>
<ul class="gs-venue">
<li><strong><?php echo $venue_name; ?></strong> | </li>
<li><?php echo $venue_street; ?></li>
<li><?php echo $venue_locality; ?>, <?php echo $venue_region; ?> <?php echo $venue_zip; ?></li>
<li><?php echo $venue_phone; ?></li>
</ul>
</div>
<div class="gs-clear"></div>
</div>
<? endforeach; ?>
</body>
Help?
Use a keyed foreach
foreach ($myfeed as $key => $goldstar):
And then unset the entire current xml using the key
unset($myfeed->$key);
Or unset just the venue with unset($myfeed->$key->venue);
Alternately, you could just build a new obj instead of trying to edit the existing one. Instantiate a new object before your loop and then only add the pieces to it that you want to keep.
Or, you can just continue the foreach if you find the unwanted venue. The only downside is that you won't have a copy of your ok'd list in $myfeed. So...
if ($venue_name == 'Hornblower Cruises and Events') { continue; }
Firstly you should cast every object that you are getting from your SimpleXML object to the relevant type. For example you should cast string attributes or nodes with putting (string) before reading the field:
$venue_name = (string)$goldstar->venue->name
For your question about filtering, I'd suggest your own way to keep looking for the match string and then decide to add or not.
EDIT
You're trying to see if the venue name is 'Hornblower Cruises and Events' then unset the current event field and echo it as XML? Firstly you should write unset($myfeed) because it's the event field itself. Next asxml would return nothing if you unset $myfeed. And you have HTML mistake in your code. In every loop of your for, you're writing:
<html>
<head></head>
<body>
You should place them before the for. And there is no closing tag for them. Put the closing tags after for. If you want to just get the fields with not venue name 'Hornblower Cruises and Events', put the <?php if($venue_name != 'Hornblower Cruises and Events') : ?> before <div class="gs-item"> and put <?php endif; ?> after </ul>.

Help with a foreach loop

In my website I am trying to display all the applicants to jobs that a user has posted, basically I want the out put to simimlar too,
Job Title 1
Aplicant Name 1
Aplicant Name 2
Applicant Name 3
Job Title 2
Applicant Name 4
Application Name 5
Basically I want the applications to be gathered under the jobs they applied for, however the out put I am current getting is,
Job Title 1
Application Name 1
Job Title 1
Applicant Name 2
The code I am using to do this foreach loop is as follows
<?php foreach($applications as $a) : ?>
<h3><?php echo $a['jobtitle']; ?></h3>
<li>
<img src="/media/uploads/candidates/<?php echo preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $a['profile_image']);?>" width="90" height="60"/>
<p><?php echo $a['name']; ?></p>
</li>
<?php endforeach; ?>
We need the data structure to properly answer, but I'm assuming you need a nested foreach...
<? foreach($jobs as $j): ?>
# list jobs
<? foreach($applicants as $a): ?>
<? if ($j['jobtitle'] == $a['jobtitle']): ?>
# list applicants
<? endif; ?>
<? endforeach; ?>
<? endforeach; ?>
Well you are getting that because you are only outputting
$a['jobtitle']
and
$a['name']
Where are the other names stored? Something like this is probably what you want, although that won't work if you copy/paste it as it seems that $applications[x]['name'] is not an array:
<?php foreach($applications as $a) : ?>
<h3><?php echo $a['jobtitle']; ?></h3>
<li>
<img src="/media/uploads/candidates/<?php echo preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $a['profile_image']);?>" width="90" height="60"/>
<?php foreach($a['name'] as $name)?>
<p><?php echo $name; ?></p>
<?php endforeach; ?>
</li>
<?php endforeach; ?>
I recommend pulling jobtitle and applicants from the database and storing them in a multidimensional array.
$jobs[$jobtitle][] = $applicant_name;
Then looping through this array in your view. I've omitted your image code for clarity.
foreach($jobs as $title=>applicants){
echo $title;
foreach($applicants as $name){
echo $name;
}
}

Categories