PHP : Create function and call it from within a foreach - php

I have this
<?php
foreach ($results as $row):
if ($row['title'] == "") $row['title'] = date('d-m-Y', strtotime($row['date']));
if (strlen($row['text']) > 100) $row['text'] = substr($row['text'], 0, 100) . "...";
?>
<div>
<a href="<?php echo $row['url'] ?>">
<img src="<?php echo $row['image'] ?>" alt="<?php echo $row['title'] ?>" />
<h1><?php echo $row['title'] ?></h1>
<p><?php echo $row['text']; ?></p>
</a>
</div>
<?php endforeach ?>
Right after the foreach starts I do some "house cleaning" where I substitute the date if there is no title and reduce the text to 100 characters etc.
Repeating this over and over is not very efficient, so it would be better to create a function right?
My question is how do I do this?
Thanks for your help

Try rewriting your code like this. Just add more of your required functionality to the processRowData() function.
<?php
function processRowData($row) {
if ($row['title'] == "") {
$row['title'] = date('d-m-Y', strtotime($row['date']));
}
// Do more with other elements from $row ...
// when done, return the modified $row array
return $row;
}
?>
<?php
foreach ($results as $row) {
// Alter the row data with your function
$row = processRowData($row);
?>
<div>
<a href="<?php echo $row['url'] ?>">
<img src="<?php echo $row['image'] ?>" alt="<?php echo $row['title'] ?>" />
<h1><?php echo $row['title'] ?></h1>
<p><?php echo $row['text']; ?></p>
</a>
</div>
<?php } ?>

Related

How to loop a php code?

I wanted to do the DRY approach in my code but I'm having a hard time figuring it out. And also, I want to hide the entire code if there's no image_1. Hope you could help me do the trick.
Here's the code
<div class="col-md-4">
<?php
$image = get_field('image_1');
if(get_field('image_1'))
{
echo '<a href="' . get_field('image_link_1') . '">';?>
<img src="<?php echo $image['url']; ?>" title="<?php echo $image['title']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php echo '</a>';
} else {
echo '<img src="http://localhost/image.png">';
} ?>
</div>
<div class="col-md-4">
<?php
$image = get_field('image_2');
if(get_field('image_2'))
{
echo '<a href="' . get_field('image_link_2') . '">';?>
<img src="<?php echo $image['url']; ?>" title="<?php echo $image['title']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php echo '</a>';
} else {
echo '<img src="http://localhost/image.png">';
} ?>
</div>
<div class="col-md-4">
<?php
$image = get_field('image_3');
if(get_field('image_3'))
{
echo '<a href="' . get_field('image_link_3') . '">';?>
<img src="<?php echo $image['url']; ?>" title="<?php echo $image['title']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php echo '</a>';
} else {
echo '<img src="http://localhost/image.png">';
} ?>
</div>
You should put differences to arrays and then wrap everything into for loop:
<?php
$images = array('image_1', 'image_2', 'image_3');
$links = array('image_link_1', 'image_link_2', 'image_link_3');
for($i=0; $i<3; $i++){
?>
<div class="col-md-4">
<?php
$image = get_field($images[$i]);
if(get_field($images[$i])){
echo '<a href="' . get_field($links[$i]) . '">';
?>
<img src="<?php echo $image['url']; ?>" title="<?php echo $image['title']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php echo '</a>';
} else {
echo '<img src="http://localhost/image.png">';
}
?>
</div>
<?php
}
?>
Just a hint...:
<?php
for ($i = 0; $i < 3; $i++) {
echo "<div class='col-md-4'>" . "\n";
$image = get_field("image_" . ($i + 1));
...
echo "</div>" . "\n";
}
?>
Something along these lines should get you started if I'm understanding you correctly:
<?php for ($q = 1; $q <= 3; $q++) {
$image_loop = 'image_' . $q;
echo '<div class="col-md-4">';
if ($image = get_field($image_loop)) {
echo '<a href="' . get_field('image_link_' . $q) . '">';
?>
<img src="<?php echo $image['url']; ?>" title="<?php echo $image['title']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php echo '</a>';
} else {
echo '<img src="http://localhost/image.png">';
} ?>
</div>
<?php } // end loop ?>
The other suggestions here will work as well but here's what I would do:
First arrange the images in an associative array with keys being the image name and values being the image link and then iterate via a foreach loop.
I generally try to not echo HTML unless strictly necessary.
<?php
$array = [
"image_1" => "image_link_1",
"image_2" => "image_link_2",
"image_3" => "image_link_3",
"image_4" => "image_link_4"
];
foreach ($array as $name => $link):
$image = get_field($name);
if ($image): ?>
<div class="col-md-4">
<a href="<?=get_field($link)?>">
<img src="<?= $image['url']; ?>" title="<?= $image['title']; ?>" alt="<?= $image['alt']; ?>" />
</a>
<?php else: ?>
<img src="http://localhost/image.png">
<?php endif; ?>
</div>
<?php endforeach; ?>

how to concatenate img src string using $i

I have trouble to concatenate img src string.
Instead of $row['img1'] I need $row['img$i']
How would I do correct concatenation using $i?
<?php $i = 1; ?>
<?php foreach ($rows as $row): ?>
<?php $item_class = ($i == 1) ? 'item active' : 'item'; ?>
<div class="<?php echo $item_class; ?>">
<img src="<?php echo '/img/post/' . $row['img1'].'.jpg'; ?>" alt="<?php echo $myrow['title']; ?>" />
</div>
<?php $i++; ?>
<?php endforeach; ?>
You can just use $row['img'.$i] or $row["img$i"] . String concatnation can be still used.

Endforeach loop different class for first item

I'm not that good at php. What i have is a list of items looped with endforeach. What I want is that the first loop will have a class of col-lg-12 and from the second one that class will become col-lg-6. How can I achive that?
Here's the code:
<?php $firstLoop = true;
foreach( $network_value as $key => $value ){
if( $firstLoop ){
echo '<div class="col-lg-12">';
}
echo '<div class="col-lg-6">';
$firstLoop = false;
} ?>
^This is the code that I've tried, but it's not working how i wanted.
<?php if ($img): ?>
<img src="<?php echo $thumb->src ?>" width="<?php echo $thumb->width ?>" height="<?php echo $thumb->height ?>" alt="" />
<?php endif; ?>
<h4>
<div class="circle"><?php echo $datePublic = date('d M', strtotime($page->getCollectionDatePublic())); ?></div>
<br>
<a class="blogTitle" href="<?php echo $url ?>" target="<?php echo $target ?>"><?php echo $title ?></a></h4>
<h6>Posted by <?php echo $author; ?></h6>
<br>
<p><?php echo $description ?></p>
</div>
<?php endforeach; ?>
The most simple way to do it is to add a counter and check if it is the first value in the counter.
<?php
$counter = 0;
foreach( $network_value as $key => $value )
{
if($counter == 0){
echo '<div class="col-lg-12">';
} else {
echo '<div class="col-lg-6">';
}
$counter++;
}
?>
Also I want to add that there are two ways of using foreach and if-statements, but you are trying to mix them, which is wrong.
The first method is using brackets "{" and "}":
foreach($users as $user) {
// do things for each user
echo $user->name; // Example of writing out users name
}
And if-statement:
if(true) {
// do something
}
The second method is using "foreach(statement):" and "endforeach;"
foreach($users as $user):
// do things for each user
echo $user->name; // Example of writing out users name
endforeach;
And if-statement:
if(true):
// do something
endif;
Edited:
In your case you can use:
<?php
foreach ($pages as $key=>$page):
if($key==0){
echo '<div class="col-lg-12">';
} if($key==1){
echo '<div class="col-lg-6">';
}
endforeach; ?>
Or you can use:
<?php
foreach ($pages as $key=>$page):
if($key==0){
echo '<div class="col-lg-12">';
} else {
echo '<div class="col-lg-6">';
}
endforeach; ?>
OLD:
foreach($array as $key=>$row){
if($key==0){
echo '<div class="col-lg-12"></div>';
}
if($key==5){
echo '<div class="col-lg-6"></div>';
}
// OR try use %
if($key%2 == 0){
echo '<div class="col-lg-12"></div>';
} else {
echo '<div class="col-lg-12"></div>';
}

Show articles in view

I have a question:
I make a pre for news:
Array
(
[0] => Array
(
[name] => tag
[id] => 57
[title] => Article1,Article2,Article3
[views] => 53,54,58
[smallimage] => Koala-08.jpg,Jellyfish-08.jpg,Mountain-08.jpg
[date] => 2014-05-07 09:21:58,2014-05-08 09:24:38,2014-05-08 14:36:40
)
)
How to create the foreach in view to show 1 title 1 views and 1 date...I create an foreach but show first all titles,all views,all dates;
My foreach:
<?php if ($news):?>
<?php foreach($news as $n):?>
<p>Tag:<?php echo $n['name'] ?></p>
<div class="container">
<img src="<?php echo config_item('content_folder');?>news/small/<?php echo $n['smallimage']; ?>" alt="">
<?php echo $n['title'] ?><br/>
<?php echo $n['views'] ?>
<?php endforeach ?>
<?php endif; ?>
With this foreach I get: Article1,Article2,Article3 53,54,58...I want to get Article1 53,Article2 54, Article3 58....Help me please
Try this:
<?php
$news = array(array( "tag",
57,
"Article1,Article2,Article3",
"53,54,58",
"Koala-08.jpg,Jellyfish-08.jpg,Mountain-08.jpg",
"2014-05-07 09:21:58,2014-05-08 09:24:38,2014-05-08 14:36:40"
) );
?>
<?php if ($news){?>
<p>Tag:<?php echo $news[0][0]; ?></p>
<div class="container">
<img src="<?php echo config_item('content_folder');?>news/small/<?php echo $news[0][4]; ?>" alt="">
<?php $views = explode(',',$news[0][3]);?>
<?php $article = explode(',',$news[0][2]);?>
<?php for($i=0;$i<count($article);$i++){
echo $article[$i].'-'.$views[$i];
} ?>
</div>
<?php }?>
I don't know where is "config_item('content_folder')" function result.Try this. And let me know whether it is works or not. Feel free to ask help.
<?php foreach($news as $n):?>
<?php $titles = explode(",", $n['title']); ?>
<?php $smallimages = explode(",", $n['smallimage']); ?>
<?php $views= explode(",", $n['views']); ?>
<p>Tag:<?php echo $n['name'] ?></p>
<div class="container">
<img src="<?php echo config_item('content_folder');?>news/small/<?php echo smallimages[0]; ?>" alt="">
<?php echo title[0] ?><br/>
<?php echo views[0] ?>
<img src="<?php echo config_item('content_folder');?>news/small/<?php echo smallimages[1]; ?>" alt="">
<?php echo title[1] ?><br/>
<?php echo views[1] ?>
<img src="<?php echo config_item('content_folder');?>news/small/<?php echo smallimages[2]; ?>" alt="">
<?php echo title[2] ?><br/>
<?php echo views[2] ?>
<?php endforeach ?>
<?php endif; ?>
I am assuming that for example 'Article1,Article2,Article3' is a string, so you would have to use:
$n['title'] = explode(',',$n['title'])
To make it into an array. Same goes for views, smallimage and date. Here's an example on how to apply that:
<p>Tag:<?php echo $n['name'] ?></p>
<div id="container">
<?php
$n['title'] = explode(',',$n['title'])
$n['views'] = explode(',',$n['views'])
$n['smallimage'] = explode(',',$n['smallimage'])
foreach ($n['title'] as $key=>$value) {
echo "<img src='" . config_item('content_folder') . "news/small" . $n['smallimage'][$key] . "' alt='' />";
echo $n['title'][$key] . "<br />";
echo $n['views'][$key]
}
?>
</div>
You would place this in the existing foreach-loop.

How to use a loop variable outside the loop?

I am trying to use $description variable outside the loop. Help me do it please.
<?php
$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());
$albums = array();
$description = "";
while ($row_album = mysql_fetch_assoc($res_album)) {
$description = $row_album['description'];
$albums[$row_album['title']] = array(
'images/albums/'.$row_album['title'].'/1.jpg',
'images/albums/'.$row_album['title'].'/2.jpg',
'images/albums/'.$row_album['title'].'/3.jpg',
'images/albums/'.$row_album['title'].'/4.jpg'
);
}
foreach ($albums as $name => $a) {
?>
<div id="album">
<a href="view_album.php?name=<?php echo $name; ?>" data-images="<?php echo implode('|', array_slice($a,1))?>" class="album">
<img src="<?php echo $a[0]?>" alt="<?php echo $name?>" />
<span class="preloader"></span>
</a>
<div class="album_info">
<h4><?php echo $name?></h4>
<p><?php echo $description; ?></p>
</div>
</div>
<?php
}
?>
Should I make an array, or define it first, i am totally confused, need help.
In your $albums array (in the while loop), store your images and description like this:
$albums[$row_album['title']] = array(
"description" => $row_album['description'],
"images" => array(
'images/albums/'.$row_album['title'].'/1.jpg',
'images/albums/'.$row_album['title'].'/2.jpg',
'images/albums/'.$row_album['title'].'/3.jpg',
'images/albums/'.$row_album['title'].'/4.jpg'
)
);
Then in your foreach loop, act like this:
<img src="<?php echo $a['images'][0]?>" alt="<?php echo $name?>" />
and
<p><?php echo $a['description']; ?></p>
Edit:
Don't forget to change this
array_slice($a,1)
to this:
array_slice($a['images'],1)
I would just combine the whole thing into a single loop; the below code is untested, but I hope you can follow it.
while ($row_album = mysql_fetch_assoc($res_album)) {
print_album($row_album);
}
function print_album(array $album)
{
$name = htmlspecialchars($album['title'], ENT_QUOTES, 'UTF-8');
$description = htmlspecialchars($album['description'], ENT_QUOTES, 'UTF-8');
$view_link = sprintf('view_album.php?%s', http_build_query([
'name' => $album['title'],
]);
$images = array_map(function($index) use ($album) {
return sprintf(
'images/albums/%s/%d.jpg',
urlencode($album['title']),
$index
);
}, range(1, 4));
$images_data = htmlspecialchars(join('|', array_slice($images, 1)), ENT_QUOTES, 'UTF-8');
?>
<div id="album">
<a href="<?php echo $view_link ?>" data-images="<?php echo $images_data; ?>" class="album">
<img src="<?php echo htmlspecialchars($images[0], ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo $name; ?>" />
<span class="preloader"></span>
</a>
<div class="album_info">
<h4><?php echo $name; ?></h4>
<p><?php echo $description; ?></p>
</div>
</div>
<?php
}
I've added escaping with the use of urlencode(), htmlspecialchars() and http_build_query() to prevent a potential break in your HTML (or XSS is the worst case).

Categories