I have seen similar questions but I feel mine is different, I have a 2 column page which needs 2 users per row, issue is when I have an array that has an odd length, the last element does not come out here is my logic
<?php for($i = 0; $i < count($team); $i++){
echo "Looping ".$i;
?>
<div class="row">
<?php for($z = $i; $z < 2; $z++){
echo "inner Looping ".$z?>
<div class="col s12 m6 grid">
<figure class="effect-honey">
<img src="<?php echo $team[$z]['image']; ?>" alt="<?php echo $team[$z]['fname']. ' '.$team[$z]['lname']; ?>"/>
<figcaption>
<h2><?php echo $team[$z]['fname']; ?><span><?php echo $team[$z]['lname']; ?></span> <i><?php echo $team[$z]['position']; ?></i></h2>
</figcaption>
</figure>
</div>
<?php $i = $z;} ?>
</div>
<?php } ?>
</div>
A sample of the output of an array with 3 items
Use array_chunk() on $team with 2 as the chunk size parameter. Then you can use an outer foreach() to iterate the generated pairs and an inner foreach() to display the subarrays.
Assuming you don't need to write empty html elements for the missing 2nd element in odd-count scenarios, here is an implementation (there are a few ways to do this).
Code (Demo)
$team = [
['image' => 'A.jpg', 'fname' => 'B', 'lname' => 'C', 'position' => 'D'],
['image' => 'E.jpg', 'fname' => 'F', 'lname' => 'G', 'position' => 'H'],
['image' => 'I.jpg', 'fname' => 'J', 'lname' => 'K', 'position' => 'L']
];
$pairs = array_chunk($team, 2);
foreach ($pairs as $pair) {
echo "<div class=\"row\">";
foreach ($pair as $player) {
echo "<div class=\"col s12 m6 grid\">";
echo "<figure class=\"effect-honey\">";
echo "<img src=\"{$player['image']}\" alt=\"{$player['fname']} {$player['lname']}\"/>";
echo "<figcaption>";
echo "<h2>{$player['fname']}<span>{$player['lname']}</span> <i>{$player['position']}</i></h2>";
echo "</figcaption>";
echo "</figure>";
echo "</div>";
}
echo "</div>";
}
Output:
<div class="row">
<div class="col s12 m6 grid">
<figure class="effect-honey">
<img src="A.jpg" alt="B C"/>
<figcaption>
<h2>B<span>C</span> <i>D</i></h2>
</figcaption>
</figure>
</div>
<div class="col s12 m6 grid">
<figure class="effect-honey">
<img src="E.jpg" alt="F G"/>
<figcaption>
<h2>F<span>G</span> <i>H</i></h2>
</figcaption>
</figure>
</div>
</div>
<div class="row">
<div class="col s12 m6 grid">
<figure class="effect-honey">
<img src="I.jpg" alt="J K"/>
<figcaption>
<h2>J<span>K</span> <i>L</i></h2>
</figcaption>
</figure>
</div>
</div>
If you require an empty (space-holding) portion of html when the "right-side" player is missing, please clarify your question / desired result.
Related
Working on a project, am pretty new to PHP and don't know how to do this in a better way.
$item_thumbnails = array(
"https://brkcdn.com/v2/images/shop/thumbnails/f7dd8e95-551f-5e1f-92f1-2ea6c29e61ca.png",
"https://brkcdn.com/v2/images/shop/thumbnails/9fd1ea9d-cfd0-525a-963f-0c3438c5dc34.png"
);
$item_names = array(
"brick-luke's Fedora",
"Golden Bok"
);
$item_urls = array(
"https://www.brick-hill.com/shop/20/",
"https://www.brick-hill.com/shop/10267/"
);
$item_values = array(
"30.000",
"100.000"
);
$item_demands = array(
"High",
"Low"
);
foreach ($item_urls as $key => $item_url) {
foreach ($item_thumbnails as $key => $item_thumbnail) {}
foreach ($item_names as $key => $item_name) {}
foreach ($item_values as $key => $item_value) {}
foreach ($item_demands as $key => $item_demand) {}
echo ('
<div class="card">
<a class="image" href="'.$item_url.'">
<img src="'.$item_thumbnail.'" onerror="this.onerror=null;this.src="'.$storageUrl.'/error.png"">
</a>
<div class="content">
<a class="header">'.$item_name.'</a>
<div class="ui divider"></div>
Value: <div class="ui right floated red horizontal label">'.$item_value.'</div>
<div class="ui divider"></div>
Demand: <div class="ui right floated green horizontal label">'.$item_demand.'</div>
</div>
</div>
');
}
It only shows the latest item in the array on all tabs (if there are more).
How to fix this? Help is appreciated.
Something like this should work:
$item_thumbnails = array(
"https://brkcdn.com/v2/images/shop/thumbnails/f7dd8e95-551f-5e1f-92f1-2ea6c29e61ca.png",
"https://brkcdn.com/v2/images/shop/thumbnails/9fd1ea9d-cfd0-525a-963f-0c3438c5dc34.png"
);
$item_names = array(
"brick-luke's Fedora",
"Golden Bok"
);
$item_urls = array(
"https://www.brick-hill.com/shop/20/",
"https://www.brick-hill.com/shop/10267/"
);
$item_values = array(
"30.000",
"100.000"
);
$item_demands = array(
"High",
"Low"
);
// iterate over one array and get values from
// other arrays under the same key `$key`
foreach ($item_urls as $key => $item_url) {
echo ('
<div class="card">
<a class="image" href="'.$item_url.'">
<img src="' . $item_thumbnails[$key] . '" onerror="this.onerror=null;this.src="'.$storageUrl.'/error.png"">
</a>
<div class="content">
<a class="header">' . $item_names[$key] . '</a>
<div class="ui divider"></div>
Value: <div class="ui right floated red horizontal label">' . $item_values[$key] . '</div>
<div class="ui divider"></div>
Demand: <div class="ui right floated green horizontal label">' . $item_demands[$key] . '</div>
</div>
</div>
');
}
First of all you should improve your array structure.
$items = array(
[
"thumbnail" => "https://brkcdn.com/v2/images/shop/thumbnails/f7dd8e95-551f-5e1f-92f1-2ea6c29e61ca.png"
"name" => "brick-luke's Fedora",
"url" => "https://www.brick-hill.com/shop/20/",
"value" => "30.000",
"demand" => "High"
],
[
"thumbnail" => "https://brkcdn.com/v2/images/shop/thumbnails/9fd1ea9d-cfd0-525a-963f-0c3438c5dc34.png",
"name" => "Golden Bok",
"url" => "https://www.brick-hill.com/shop/10267/",
"value" => "100.000",
"demand" => "Low"
]
);
After that you can foreach $items variable and take data from it. See below:
<?php
foreach ($items as $item) {
?>
<div class="card">
<a class="image" href="<?php echo $item['url']; ?>">
<img src="<?php echo $item['thumbnail']; ?>" onerror="this.onerror=null;this.src=<?php echo $storageUrl; ?>/error.png">
</a>
<div class="content">
<a class="header"><?php echo $item['name']; ?></a>
<div class="ui divider"></div>
Value: <div class="ui right floated red horizontal label"><?php echo $item['value']; ?></div>
<div class="ui divider"></div>
Demand: <div class="ui right floated green horizontal label"><?php echo $item['demand']; ?></div>
</div>
</div>
<?php
}
?>
Enjoy!
I'm wondering what is the best practice to embed tags in a foreach loop?
I have an associative array which has one entry with the following keys:
$portfolio = [
'title' => '',
'technology' => '',
'description' => '',
'link' => '',
];
What I am trying to do is echo the div tag with the specific elements inside, but each div tag is then duplicated:
<div class="container">
<div class="row">
<div class="col-md-6 col-lg-4"><div class="card">\n<div class="car img
top"></div>
</div>
</div><div class="col-md-6 col-lg-4"><div class="card"><div class="car
img top"></div>
</div>
</div><div class="col-md-6 col-lg-4"><div class="card"><div class="car
img top"></div>
</div>
</div><div class="col-md-6 col-lg-4"><div class="card"><div class="car
img top"></div>
</div>
</div> </div><!-- row end -->
</div><!-- container end -->
My foreach loop is:
I have commented some out, as I'm in the process of debugging as when the page is loaded a white page appears, which the error is within the commented out code, which I will fix.
foreach($portfolio as $value){
echo '<div class="col-md-6 col-lg-4">' . '\n';
echo '<div class="card">' . '\n';
echo '<div class="car img top">';
//echo "<img src='img/" . "$value['image']'" . ">";
//echo "</div>";
//echo "<div class='card-body'>";
// echo "<div class='card-body'>";
// echo "<h3 class'card-title'><a class='text-secondary' href='#'>See Project</a></h3>";
// echo "<h6 class='card-subtitle mb-2 text-muted'>$value['description']</h6>";
echo "</div>". "\n";
echo "</div>" . "\n";
echo "</div>";
}
Any help would be appreciated, but I think my best aim is to do a multidimensional array?
Thanks,
James
If your problem is only a formatting and legibility one, try to use this syntax instead.
<?php foreach($portfolio as $value):?>
<div class="col-md-6 col-lg-4">
<div class="card">
<div class="car img top">
<img src="img/<?php echo $value['image'];?>" />
</div>";
<div class="card-body">
<div class="card-body">
<h3 class='card-title'>
<a class='text-secondary' href='<?php echo $value['link']?>'>
<?php echo $value['title']?>
</a>
</h3>
<h6 class='card-subtitle mb-2 text-muted'><?php echo $value['description']?></h6>
</div>
</div>
</div>
</div>
<?php endforeach;?>
Notice that you had mistakes on your quotes and you had forgotten the closing div tag. This format makes it easier to read and catch mistakes.
Note in my example, I assume that your $portfolio variable is a multi-dimensional array as such:
$portfolio = [
[
'title' => '',
'technology' => '',
'description' => '',
'link' => ''
],
[
'title' => '',
'technology' => '',
'description' => '',
'link' => ''
],
// etc
];
I would like to create a new containing <div> after 3 results, using PDO result loop.
For my self-study-project I have to made a product page with bootstrap and after every 3rd record I have to make a new row and show again 3 col-md-4's, etc, etc.
Now I have this as my code:
<div class="row">
<?php
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
?>
<div class="col-md-4">
<div class="product">
<div class="title"><?php echo $row->pname ?></div>
<div class="img"><img
src="../product/img/<?php echo $row->pnumber ?>/<?php echo $row->pthumbnail ?>.jpg?$pop210x210$"/>
</div>
<div class="vijftien"></div>
<div class="deliver">Levertijd: <strong><?php echo $row->pdelivertime ?></strong></div>
<div class="vijf"></div>
<div class="other"></div>
<div class="row">
<div class="col-md-6">
<div class="price"><?php echo $row->pprice ?></div>
</div>
<div class="col-md-6">
<div class="order">
<button class="log_in" id="doLogin">Meer informatie</button>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
I have visited and studied other questions but I do not really get the idea of how they are doing it and how I can implement the correct method into my code.
As tadman stated in the comment under your question. The best approach should use a modulus operator (%) with 3.
Place your separating condition at the start of each iteration. (Demo)
Like this:
$x=0; // I prefer to increment starting from zero.
// This way I can use the same method inside a foreach loop on
// zero-indexed arrays, leveraging the keys, and omit the `++` line.
echo "<div class=\"row\">";
foreach($rows as $row){
if($x!=0 && $x%3==0){ // if not first iteration and iteration divided by 3 has no remainder...
echo "</div>\n<div class='row'>";
}
echo "<div>$row</div>";
++$x;
}
echo "</div>";
This will create:
<div class="row"><div>one</div><div>two</div><div>three</div></div>
<div class='row'><div>four</div><div>five</div><div>six</div></div>
Late Edit, here are a couple of other methods for similar situations which will provide the same result:
foreach(array_chunk($rows,3) as $a){
echo "<div class=\"row\"><div>",implode('</div><div>',$a),"</div></div>\n";
}
or
foreach ($rows as $i=>$v){
if($i%3==0){
if($i!=0){
echo "</div>\n";
}
echo "<div class=\"row\">";
}
echo "<div>$v</div>";
}
echo "</div>";
To clarify what NOT to do...
Sinan Ulker's answer will lead to an unwanted result depending on the size of your result array.
Here is a generalized example to expose the issue:
Using this input array to represent your pdo results:
$rows=["one","two","three","four","five","six"];
Sinan's condition at the end of each iteration:
$i=1;
echo "<div class=\"row\">";
foreach($rows as $row){
echo "<div>$row</div>";
if($i%3==0)echo "</div>\n<div class='row'>"; // 6%3==0 and that's not good here
// 6%3==0 and will echo the close/open line after the content to create an empty, unwanted dom element
$i++;
}
echo "</div>\n\n";
Will create this:
<div class="row"><div>one</div><div>two</div><div>three</div></div>
<div class='row'><div>four</div><div>five</div><div>six</div></div>
<div class='row'></div> //<--- this extra element is not good
You need to add a new closure tag and open new one every 3th iteration.
<div class="row">
<?php
$sql = "SELECT * FROM products";
$stmt = $conn->query($sql);
$stmt->execute();
$i=1;
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
?>
<div class="col-md-4">
<div class="product">
<div class="title"><?php echo $row->pname ?></div>
<div class="img"><img
src="../product/img/<?php echo $row->pnumber ?>/<?php echo $row->pthumbnail ?>.jpg?$pop210x210$"/>
</div>
<div class="vijftien"></div>
<div class="deliver">Levertijd: <strong><?php echo $row->pdelivertime ?></strong>
</div>
<div class="vijf"></div>
<div class="other"></div>
<div class="row">
<div class="col-md-6">
<div class="price"><?php echo $row->pprice ?></div>
</div>
<div class="col-md-6">
<div class="order">
<button class="log_in" id="doLogin">Meer informatie</button>
</div>
</div>
</div>
</div>
</div>
<?php
if($i%3==0)echo "</div><div class='row'>";
$i++;
} ?>
$x = 0;
echo "";
foreach($rows as $row)
{
/* added one more condition for removing empty div.... */
if ($x != 0 && $x % 3 == 0 && $x < count($rows))
{
echo "</div>\n<div class='row'>";
}
echo "<div>$row</div>";
++$x;
}
echo "";
I have this most annoying problem; I'm trying to arrange three divs on a row, and then new row, and another three divs and so on, like this:
<div class="container">
<div class="row">
<div class="col-sm-1">1</div>
<div class="col-sm-1">2</div>
<div class="col-sm-1">3</div>
</div>
<div class="row">
<div class="col-sm-1">4</div>
<div class="col-sm-1">5</div>
<div class="col-sm-1">6</div>
</div>
</div>
As for this accepted answer,
There is one catch: 0 % 3 is equal to 0. This could result in
unexpected results if your counter starts at 0.
So how would i implement this into this code:
<div class="col-md-8">
<?php
foreach($this->movies->movie_data as $key => $movie){
$string = file_get_contents("http://example.com/?t=" . urlencode($movie->movie_titel). "&y=&plot=short&r=json");
$result = json_decode($string);
if($result->Response == 'True'){
?>
<div class="col-sm-4">
<?php if($result->Poster == 'N/A') : ?>
<a href="<?php echo Config::get('URL')?>ladybug/day/<?php echo $this->city ?>/<?php echo $movie->movie_id ?>">
<img src="<?php echo Config::get('URL')?>/images/na.png" class="img-responsive img-thumbnail"></a>
<?php else: ?>
<a href="<?php echo Config::get('URL')?>ladybug/day/<?php echo $this->city ?>/<?php echo $movie->movie_id ?>">
<img src="<?php echo $result->Poster; ?>" class="img-responsive img-thumbnail"></a>
<?php endif; ?>
<div><b><?php echo $result->Title; ?></b></div>
<div><i><?php // echo $result->Plot; ?></i></div>
</div>
<?php }else{ ?>
<div class="col-sm-4">
<a href="<?php echo Config::get('URL')?>ladybug/day/<?php echo $this->city ?>/<?php echo $movie->movie_id ?>">
<img src="<?php echo Config::get('URL')?>/images/na.png" class="img-responsive img-thumbnail"></a>
<div><b><?php echo $movie->movie_titel ?></b></div>
<div class="plot"><i><?php //echo 'N/A' ?></i></div>
</div>
<?php }}} ?
</div>
For some reason, divs is arranged like this:
My question: How do I arrange thumbnails on a new row, every third time?
Found the answer in the other Q... Didn't read, sorry about that.
<?php }
if (($key + 1) % 3 == 0) { ?>
</div>
<?php }
}} ?>
I'm attempting to get a list of users who searched a term on Twitter and so far no luck. Here's my code:
$parameters = array('q' => '#puppy', 'count' => 2);
$results = $connection->get('search/tweets', $parameters);
//print_r($result);
foreach ($results as $data) {
?>
<div id="update">
<div id="left"><a href="https://twitter.com/#!/<?php echo $data->user->screen_name; ?>" target="_blank"/><img width="48px" height="48px" src="<?php echo $data->user->profile_image_url; ?>"/></a></div>
<div id="right">
<div class="user"><a href="https://twitter.com/#!/<?php echo $data->user->screen_name; ?>" target="_blank"/><?php echo $data->user->screen_name; ?></a> <?php echo $data->user->name; ?></div>
<div class="detail">
<?php echo $data->text; ?>
</div>
</div>
</div>
<?php
}
and this is what it outputs:
Notice: Undefined property: stdClass::$user in line 150
Trying to get property of non-object in line 150
I know I'm accessing that array in a weird way, I just can't figure out how it needs to be.
For anyone out there who may be needing this, it was just a matter of getting the right data from the array in the right way. Here's the code I used:
$parameters = array('q' => '#puppy', 'count' => 2);
$results = $connection->get('search/tweets', $parameters);
$resultsuser = $results->statuses[0]->user;
$i = 0;
foreach ($results->statuses as $data) {
$user_screen_name = $data->user->screen_name;
$user_profile_image_url = $data->user->profile_image_url;
$user_text = $data->text;
?>
<div id="update">
<div id="left"><a href="https://twitter.com/#!/<?php echo $user_screen_name; ?>" target="_blank"/><img width="48px" height="48px" src="<?php echo $user_profile_image_url; ?>"/></a></div>
<div id="right">
<div class="user"><a href="https://twitter.com/#!/<?php echo $user_screen_name; ?>" target="_blank"/><?php echo $user_screen_name; ?></a> <?php echo $user_screen_name; ?></div>
<div class="detail">
<?php echo $user_text; ?>
<hr/>
</div>
</div>
</div>
<?php
$i++;
}
?>