Please forgive the extreme beginner coding style. This is my first time working with PHP and JSON strings from an API.
What I'm trying to do here, which obviously does not work, if you are viewing it, prints out a few videos that the user is looking for. This is a search results page - with a movie poster and some key details next to each item.
One of the things I need next to each result is a list of the first 5 actors listed in the film as "Star Game", and then all the directors listed in the film as "Director."
The problem, no doubt, is that I have embedded foreach instructions. But I do not know another way to do this.
Please, please, the simplest answer would be the best for me. I do not mind if this is bad practice, just any solution that will be the fastest would be perfect!
Here is the code:
if ($films_result == '["Nothing found."]' || $films_result == null) {
}
else {
foreach ($films as $film) {
$backdrop_url = 'images/placeholder-film.gif';
foreach($film->backdrops as $backdrop) {
if ($backdrop->image->size == 'thumb') {
$backdrop_url = $backdrop->image->url;
}
}
echo '<div class="view-films-film">
<a href="film.php?id=' . $film->id . '"><img src="' . $backdrop_url . '" alt="' . strtolower($film->name) . '" /></a>
<div class="view-films-film-snippet">
<h2><a href="film.php?id=' . $film->id . '">' . strtolower($film->name) . '</a></h2>
<img src="images/bbfc-' . strtolower($film->certification) . '.png" alt="" />
<h3>Starring</h3>
<p>';
$num_actors = 0;
foreach ($films[0]->cast as $cast) {
if ($cast->job == 'Actor') {
echo '<a href="person.php?id=' . $cast->id . '">' . $cast->name . '</a> ';
$num_actors++;
if ($num_actors == 5)
break;
}
}
echo ' </p>
<h3>Director</h3>
<p>';
foreach ($films[0]->cast as $cast) {
if ($cast->job == 'Director') {
echo '<a href="person.php?id=' . $cast->id . '">' . $cast->name . '</a> ';
}
}
echo ' </p>
</div>
</div>';
}
}
An example of the result could be the following:

with line 120 being foreach ($films[0]->cast as $cast) {and line 131 is equalforeach ($films[0]->cast as $cast) {
source
share