Values in foreach cannot indicate - php

index.php:
<?php
$st = $pdo->query("SELECT * FROM post WHERE parent=0 ORDER BY no DESC");
$posts = $st->fetchAll();
for($i = 0;$i < count($posts); $i++){
$st = $pdo->query("SELECT * FROM post WHERE parent={$posts[$i]['no']} ORDER BY no");
$posts[$i]['child'] = $st->fetchAll();
}
require 'd_index.php';
?>
d_design.php:
foreach($posts as $post) { ?>
<div class="post_parent">
<h3>no:<?php echo $post['no'] . "Title:" . $post['title'] ?></h3>
<p><?php echo $post['name'] ?></p>
<p><?php echo nl2br($post['content']) ?></p>
<p>comment</p>
<p><small>posted:<?php echo $post['time'] ?></small></p>
<?php foreach($post['child'] as $child) { ?>
<div class="post_child">
<h4>no:<?php echo $child['no'] . "Title:" . $child['title'] ?></h4>
<p><?php echo $child['name'] ?></p>
<p><?php echo nl2br($child['content']) ?></p>
<p><small>posted:<?php echo $child['time'] ?></small></p>
</div>
<?php } ?>
</div>
<?php } ?>
I want to nest the foreach, but in this code, the second foreach($child) can't indicate.

You can achive this by making your loop recursive. Example:
function loop_posts($posts) {
foreach($posts as $post) {
echo $post->name;
if (isset($post['child'])) {
loop_posts($post['child']);
}
}
}
loop_posts($posts);

Related

Get two adjacent images in a while loop PHP

I have a html code , when i convert into php some issues happended . Actually i need a foreach or while loop for the below div.
But all images are different (never mind the names of images, it can be any name).
<div class='img'>
<img src='img/1.jpg'>
<img src='img/2.jpg'>
</div>
<div class='img'>
<img src='img/3.jpg'>
<img src='img/4.jpg'>
</div>
//....more divs like this
Here my try
$stmt=$db->query("Select * from photo");
foreach ($stmt as $row)
{
?>
<div class='img'>
<img src='img/<?php echo $row['image']; ?>'>
<img src='img/<?php echo $row['image']; ?>'> // how to get this image diffent from above images
</div>
<?php }
Any experts?
Try that:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare("SELECT * FROM photo");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
?>
<?php $i = 0; ?>
<?php $response = array(); ?>
<?php foreach ($data as $dataIndex => $dataValue): ?>
<?php if ($i == 1): ?>
<?php $response[] = '<img src="img' . $dataValue["image"] . '"/>'; ?>
<?php $response[] = "</div>"; ?>
<?php $i = 0; ?>
<?php else: ?>
<?php $response[] = "<div class='img'>"; ?>
<?php $response[] = '<img src="img' . $dataValue["image"] . '"/>'; ?>
<?php $i++; ?>
<?php endif; ?>
<?php endforeach; ?>
<?php if(count($data)%2): ?>
<?php $response[] = "</div>"; ?>
<?php endif; ?>
<?php echo implode("", $response); ?>
output:
<div class="img">
<img src="img1">
<img src="img2">
</div>
<div class="img">
<img src="img3">
<img src="img4">
</div>
<div class="img">
<img src="img5">
<img src="img6">
</div>
Assuming $stmt is an array, you can do this.
<?php
$count = 0
while(sizeof($stmt) > $count) {
?>
<img src="<?php $stmt[$count]['image']?>"/>
<?php
$count++;
?>
<img src="<?php $stmt[$count]['image']?>"/>
<?php $count++; ?>
}
?>

Php foreach loop wrapped every 2items with a row

<div class="puffar">
<?php
//Set up the objects needed
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));
//Get children
$children = ($post->post_parent) ? get_page_children($post->post_parent, $all_wp_pages) : get_page_children($post->ID, $all_wp_pages);
$i = 0;
//Build custom items
echo "<div class='row'>";
foreach ($children as $child) {
?>
<div class="col-sm-6">
<div class="puff">
<div class="puff-image-holder">
<?php echo get_the_post_thumbnail($child->ID, 'full'); ?>
</div>
<fieldset class="linedHeadline hlmedium">
<legend><?php echo get_the_title($child->ID); ?></legend>
</fieldset>
<?php echo get_field("puff_introtext", $child->ID); ?>
<?php
$values = get_field('puff_lanktext', $child->ID);
if (get_field("popup_eller_lank", $child->ID) == "popup") {
?>
<fieldset class="linedHeadline hlmedium">
<legend><a class="linktopage open-popup"
href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field("puff_lanktext", $child->ID); ?> </a>
</legend>
</fieldset>
<?php
} elseif (get_field("popup_eller_lank", $child->ID) == "extern") {
?>
<fieldset class="linedHeadline hlmedium">
<legend><a class="linktopage"
href="<?php echo get_field("puff_lank", $child->ID); ?>"><?php echo get_field("puff_lanktext", $child->ID); ?> </a>
</legend>
<?php
$i++;
if ($i % 2 == 0) {
echo "</div><div class='row'>";
}
} else {
}
?>
</div>
</div>
<?php } ?>
</div>
</div>
I want every 2 items that's rendered out to be wrapped in a <div class="row">, however I can't figure it out. Can anyone help me?
So basically the row should wrap every 2 elements that is getting looped. I have been stuck on this forever... Hopefully anyone got better expertise than me hehe.
The div="row" should wrap the col-sm-6 and class="puff".
$i = 0;
foreach ($children as $child) {
$i++;
// your code goes here
if($i % 2 == 0) {
echo "</div><div class='row'>";
// reset the counter to 0
$i = 0 ;
}
}
use proper logic
if ($i % 2 == 0) {
echo "</div><div class='row'>";
}
$i++;
First check if its mod by 2 or not (Gives 0 value after MOD), then close div , open new.
Now increase counter . Because for the first time , i will be 0 , then you increment it and then you use logic. So in short counter shoul be incremented at the end only not in between before you do any operation/logic.
Updated
Use code as it is **: issue was you have i++ and your condition in 3rd else if which never executed. So took it outside All and just before foreach.
<div class="puffar">
<?php
//Set up the objects needed
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));
//Get children
$children = ($post->post_parent) ? get_page_children($post->post_parent, $all_wp_pages) : get_page_children($post->ID, $all_wp_pages);
$i = 0;
//Build custom items
echo "<div class='row'>";
foreach ($children as $child) {
?>
<div class="col-sm-6">
<div class="puff">
<div class="puff-image-holder">
<?php echo get_the_post_thumbnail($child->ID, 'full'); ?>
</div>
<fieldset class="linedHeadline hlmedium">
<legend><?php echo get_the_title($child->ID); ?></legend>
</fieldset>
<?php echo get_field("puff_introtext", $child->ID); ?>
<?php
$values = get_field('puff_lanktext', $child->ID);
if (get_field("popup_eller_lank", $child->ID) == "popup") {
?>
<fieldset class="linedHeadline hlmedium">
<legend><a class="linktopage open-popup"
href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field("puff_lanktext", $child->ID); ?> </a>
</legend>
</fieldset>
<?php
} elseif (get_field("popup_eller_lank", $child->ID) == "extern") {
?>
<fieldset class="linedHeadline hlmedium">
<legend><a class="linktopage"
href="<?php echo get_field("puff_lank", $child->ID); ?>"><?php echo get_field("puff_lanktext", $child->ID); ?> </a>
</legend>
<?php
} else {
}
?>
</div>
</div>
<?php
if ($i % 2 == 0) {
echo "</div><div class='row'>";
}
$i++;
} ?>
</div>
</div>
First set $i=0;
if ($i % 2 == 0) {
echo "</div><div class='row'>";
}
$i++;

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>';
}

Select one row at a time from a query with multiple rows?

I have a query that selects 3 rows; but I only want to display the one row at a time, use the data from that row, then move to the next row, then repeat. How would this be accomplished? Table has 4 items in it.
PHP:
<?php
$server = "secret";
$user = "secret";
$pass = "secret";
$db = "secret";
$con=mysqli_connect($server,$user,$pass,$db);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = 'SELECT * FROM news ORDER BY id DESC LIMIT 3';
mysqli_select_db($con, $db);
$query = mysqli_query($con, $sql);
$number = 1;
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
}
mysqli_close($con);
?>
Attempt to display:
<div name='title'><?php echo $title; ?></div> || <div name='news_date'><?php echo $news_date; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post; ?></p>
<?php
$number++;
?>
Output of attempt:
Test
||
7/14/13
News 1
Testing to see if this will work lalalalalla
NOTE: Tried to repeat the attempt to see if it would work, but it displayed same as output but with a second one that was a duplicate except said News 2
Desired output look:
Newest Title | Newest Date
Newest news. Etc. Insert Big Paragraph of news here etc etc.
2nd Newest Title | 2nd Newest Date
2nd Newest news. Etc. Insert Big Paragraph of news here etc etc.
3rd Newest Title | 3rd Newest Date
3rd Newest news. Etc. Insert Big Paragraph of news here etc etc.
The problem is that you are overwriting your variables with each while() loop -
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
}
so when you try to echo $id, $title, $news_date, and $post, you will only get the last row data
you either need to add your html in the while loop -
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
?>
<div name='title'><?php echo $title; ?></div> || <div name='news_date'><?php echo $news_date; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post; ?></p>
<?php
$number++;
}
or save them to an array
$id = array();
$title = array();
$news_date = array();
$post = array();
while ($result = mysqli_fetch_array($query)) {
$id[] = $result['id'];
$title[] = $result['title'];
$news_date[] = $result['news_date'];
$post[] = $result['post'];
}
and then access the array in your display
<div name='title'><?php echo $title[$number-1]; ?></div> || <div name='news_date'><?php echo $news_date[$number-1]; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post[$number-1]; ?></p>
<?php
$number++;
?>
I used [$number-1] as I assume $number is starting at 1, and arrays are 0 based
edit here are ways to echo your html. It would be beneficial to visit the php documentation, as all of this is there. In these I set $number back to 0, but you can change it back to 1, and just change each of the $number->$number-1, and the $number+1->$number
using a for loop - http://php.net/manual/en/control-structures.for.php
<?php
for($number=0;$number<count($title);$number++){
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
}
?>
using a foreach loop - http://php.net/manual/en/control-structures.foreach.php
<?php
foreach($title as $number => $value{
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
}
?>
using a while loop - http://php.net/manual/en/control-structures.while.php
<?php
$number = 0;
while($number<count($title){
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
$number++;
}
?>
each of the above was done by closing out of php, and writing the html, and then opening php again. You could also just stay in php, and echo the html - http://php.net/manual/en/function.echo.php
<?php
for($number=0;$number<count($title);$number++){
echo "<div name='title'>".$title[$number]."</div> || <div name='news_date'>".$news_date[$number]."</div>";
echo "<p>News ".($number+1)."</p>";
echo "<p>".$post[$number]."</p>";
}
?>

Find last row in a foreach query

How could I find the last post and NOT put <hr> below it?
<?php foreach($db->query("SELECT * FROM news") as $row): ?>
<div class="NewsHeadline">
<div class="NewsDate"><?php echo $date; ?> - </div>
<div class="NewsTitle"><?php echo $title; ?></div>
</div>
<div class="NewsBody">
<?php echo $body; ?>
</div>
<hr>
<?php endforeach ?>
Set a counter equal to 1 which increments each round, and check if it is equal to the count() of the $query array returned. If it is, you are on the last round!
<?php
$counter = 1;
$total = count($db->query("SELECT * FROM news"));
?>
<?php foreach($db->query("SELECT * FROM news") as $row): ?>
<div class="NewsHeadline">
<div class="NewsDate"><?php echo $date; ?> - </div>
<div class="NewsTitle"><?php echo $title; ?></div>
</div>
<div class="NewsBody">
<?php echo $body; ?>
</div>
<?php if($counter != $total){
?>
<hr>
<?php
}
?>
<?php $counter++; ?>
<?php endforeach ?>
A solution would be to build an array and then use join :
<?php
$arr=array();
foreach($db->query("SELECT * FROM news") as $row):
$arr[] = '<div class="NewsHeadline"><div class="NewsDate">'.$date
.' - </div><div class="NewsTitle">'.$title'
.</div></div><div class="NewsBody">'.$body.'</div>';
endforeach
echo join("<hr>",$arr);
?>
You can convert to regular for loop and then compare $i to the size of your query result:
<?php
$news = $db->query("SELECT * FROM news");
for($i=0; $i<sizeof($news);$i++){ ?>
<div class="NewsHeadline">
<div class="NewsDate"><?php echo $date; ?> - </div>
<div class="NewsTitle"><?php echo $title; ?></div>
</div>
<div class="NewsBody">
<?php echo $body; ?>
</div>
<?php if(($i+1) < sizeof($news)) echo '<hr>'; ?>
<?php } ?>
If you get a count of the rows prior to the loop, you can check the count and avoid adding the HR.
$rows = $db->query("SELECT * FROM news");
$row_count = $rows.count();
$iter = 0;
foreach($rows as $row)
{
//...
if ($iter < $row_count)
{
// render hr
}
$iter++;
}
You could also go with a pure CSS approach:
div.containerClass:last-child hr { display:none; }
where "containerClass" would be whatever element your posted code sits inside of.

Categories