I'm relatively new to php and I've been trying all day long to get this to work. I have a multiple array and want to echo each one in a specific format, and in groups.
So i've gone through stackoverflow and found this help:
<? foreach(array_chunk($projetos, 6) as $curta ) { ?>
<li style='display:block'>
<div class="film"> <?php echo $curta[0]['titulo']; ?></div>
<div class="film"> <?php echo $curta[1]['titulo']; ?></div>
<div class="film"> <?php echo $curta[2]['titulo']; ?></div>
<div class="film"> <?php echo $curta[3]['titulo']; ?></div>
<div class="film"> <?php echo $curta[4]['titulo']; ?></div>
<div class="film"> <?php echo $curta[5]['titulo']; ?></div>
</li>
<? }; ?>
And this returns what I want but the last items of the array doesnt fill up to 6 and creates 2 extras empty divs and messes up the design.
This is a single example of the array i have:
<?php
$projetos = array (
"ugm" => array (
"id" => "ugm",
"titulo" => "Una Guerra Más",
"video" => "imagem",
"videoid" => "",
"height" => "$video_height_wide",
"sinopse" => "Um soldado moribundo deseja enviar sua última carta. Curta indisponível por exibição em festivais. Feito em parceria com a Universidad del Cine e LightBox Studios.",
"elenco" => "Ignacio J. Durruty - Rodrigo Soler - Ulisses Levanavicius - Aron Matschulat Aguiar",
"idioma" => "Inglês - Português",
"camera" => "Sony EX1",
"formato" => "HD",
"duracao" => "9'55''",
"ano" => "2012",
"tipo" => "Curta",
"credito" => "Direção - Edição - Produção - Roteiro",
), (...)
I want to be able to edit just one div that will be the master for the others... and using the implode I've read on another question but didn't worked to echo the strings I wanted..
Would please someone help out?
thanks in advance!
<?php foreach(array_chunk($projetos, 6) as $curta ) { ?>
<li style='display:block'>
<?php foreach($curta as $detail) { ?>
<div class="film"> <?php echo $detail['titulo']; ?></div>
<?php } ?>
</li>
<? }; ?>
Why not use a loop to iterate over $curta?
<? foreach(array_chunk($projetos, 6) as $curta ) { ?>
<li style='display:block'>
<? foreach($curta as $c) { ?>
<div class="film"><? echo $c['titulo']; ?></div>
<? } ?>
</li>
<? }; ?>
but the last items of the array doesnt fill up to 6
As this is going to happen most of the time, you can't assume that every chunk has 6 elements, so you'll have to iterate over the chunk:
<? foreach(array_chunk($projetos, 6) as $curta ) { ?>
<li style='display:block'>
<? foreach($curta as $c) { ?>
<div class="film"> <?php echo $c['ugm']['titulo']; ?></div>
<? }; ?>
</li>
<? }; ?>
This way you are sure to display no empty divs.
This lines:
<div class="film"> <?php echo $curta[0]['titulo']; ?></div>
should be like this:
<div class="film"> <?php echo $curta[0]['ugm']['titulo']; ?></div>
that should do what you want.
Related
So here is my code. The problem I am having is that I want the number from HP in my PHP code into my HP HTML code and the same thing with Cylinders. I have figured out the other stuff but when it comes to that part I am stuck
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$cars = array(
array(
"car" => "Ferrari",
"model" => "Testarossa",
"gearbox" => "Manual 5 Shift",
"designer" => "Battista Pininfarina",
"engine" =>
array(
"HP" => 390,
"Cylinders" => 12
),
),
);
?>
<?php foreach($cars as $cars_key => $car_val): ?>
<ul>
<div style="margin-bottom: 10px;">
<li><b>Car:</b> <?php echo $car_val["car"]; ?></li>
<li><b>Model:</b> <?php echo $car_val["model"]; ?></li>
<li><b>Gearbox:</b> <?php echo $car_val["gearbox"]; ?></li>
<li><b>Designer:</b> <?php echo $car_val["designer"]; ?></li>
<li><b>Engine</b></li>
<ul>
<li><b>HP:</b></li>
<li><b>Cylinders:</b></li>
</ul>
</div>
</ul>
<?php endforeach; ?>
I have a few concerns:
You lose the brilliance/utility of an associative array when you hardcode values into your script that you could otherwise just call from the array.
I don't like the look of the mid-list <div>. I can't think of any good reason to break up your unorder list flow with it.
I don't like the floating sub-list either. It logically belongs to Engine and good markup would dictate that the sub-list exist inside of its parent.
Here is what I would suggest considering my above points...
*Some Notes:
I'm not sure how you want to layout multiple lists as your array grows in size.
The echoing is just my personal preference. You can bounce in and out of php if you like.
ucfirst() allows you to avoid hardcoding the keys.
My snippet will make your task clean, DRY, and concise.
Code: (Demo)
$cars = array(
array(
"car" => "Ferrari",
"model" => "Testarossa",
"gearbox" => "Manual 5 Shift",
"designer" => "Battista Pininfarina",
"engine" => array(
"HP" => 390,
"Cylinders" => 12
)
)
);
foreach($cars as $details){
echo "<ul style=\"margin-bottom:10px;\">";
foreach($details as $key=>$item){
echo "<li><b>",ucfirst($key),":</b>";
if(!is_array($item)){
echo " $item</li>";
}else{
echo "<ul>";
foreach($item as $subkey=>$subval){
echo "<li><b>$subkey:</b> $subval</li>";
}
echo "</ul>";
echo "</li>";
}
}
echo "</ul>";
}
Source Code Output:
<ul style="margin-bottom:10px;">
<li><b>Car:</b> Ferrari</li>
<li><b>Model:</b> Testarossa</li>
<li><b>Gearbox:</b> Manual 5 Shift</li>
<li><b>Designer:</b> Battista Pininfarina</li>
<li><b>Engine:</b>
<ul>
<li><b>HP:</b> 390</li>
<li><b>Cylinders:</b> 12</li>
</ul>
</li>
</ul>
Rendered Output: (run my snippet # phptester.net to see this)
From you example, it seems to me that the list is static and consists of two elements, then you need not use forEach at all.
<?php foreach($cars as $cars_key => $car_val): ?>
<ul>
<div style="margin-bottom: 10px;">
<li><b>Car:</b> <?php echo $car_val["car"]; ?></li>
<li><b>Model:</b> <?php echo $car_val["model"]; ?></li>
<li><b>Gearbox:</b> <?php echo $car_val["gearbox"]; ?></li>
<li><b>Designer:</b> <?php echo $car_val["designer"]; ?>
</li>
<li><b>Engine</b></li>
<ul>
<li><b>HP:</b><?php echo $car_val["engine"]["HP"]; ?></li>
<li><b>Cylinders:</b><?php echo $car_val["engine"]["Cylinders"]; ?></li>
</ul>
</div>
</ul>
<?php endforeach; ?>
If you do need to use a nested forEach, here is how you would go about doing that:
foreach($cars as $cars_key => $car_val):
if($cars_key == "engine")
foreach($car_val["engine"] as $engine_key => $engine_val):
echo $engine_key.$engine_val;
endforeach;
endforeach;
I'm new to CakePHP, I was wondering if there is a way to echo information from the database using a foreach loop but only have HTML links on images where the id is 1 & 7. What's the best way of achieving this?
<?php if ( isset($articles) ){ ?>
<?php foreach($articles as $article):?>
<?php echo ($this->Html->image($article['Post']['picture'], array('alt' => 'storyimage', 'class' => 'smallimg'));?>
<h3 class="caps"><?php echo $article['Post']['genre'];?></h3>
<h2><?php echo $article['Post']['story'];?></h2>
<div id="contentbox2">
</div>
<?php endforeach; ?>
<?php } ?>
This is how it looks in the veiw, my database in looks image data is stored like this:
suki-burberry-sq_500_500_90_s_c1.jpg
Would it be best to echo all the data individually without the foreach loop or could I write an if statement?
If you want only to get the 1 & 7 id you can do this, assuming that it is a predefined number. If it is dynamic or changeable you can do that in your controller.
<?php if ( isset($articles) ){ ?>
<?php foreach($articles as $article):?>
<?php if ($article['Post']['id']==1 || if ($article['Post']['id']==7) ): ?>
<?php echo ($this->Html->image($article['Post']['picture'], array('alt' => 'storyimage', 'class' => 'smallimg'));?>
<h3 class="caps"><?php echo $article['Post']['genre'];?></h3>
<h2><?php echo $article['Post']['story'];?></h2>
<div id="contentbox2">
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php } ?>
Best way is to find from your Model only what you needed.
with the condition $conditions=array('Post.id'=>array(1,7));
I have this code, and I need to close a row every 4 post. Every post is inside a div. I tried some things but I coudn't implement to my code.
<?php
echo "<div class='row'>";
global $post;
$all_events = tribe_get_events(
array(
'eventDisplay'=>'upcoming',
//'posts_per_page'=>10,
)
);
foreach($all_events as $post) {
setup_postdata($post);
?>
<div class="col-sm-3">
<span class="event-date"><?php echo tribe_get_start_date($post->ID, true, 'j M'); ?></span>
<h3><?php the_title(); ?></h3>
<?php if ( has_post_thumbnail() ) { ?>
<div class="event-thumb">
<?php the_post_thumbnail('thumbnail'); ?>
</div>
<div class="event-excerpt">
<?php the_excerpt(); ?>
</div>
<?php } else { ?>
<div class="event-content">
<?php the_content(); ?>
</div>
<?php } ?>
</div>
<?php } //endforeach ?>
<?php wp_reset_query(); ?>
<?php
echo "<div class='row'>";
global $post;
$all_events = tribe_get_events(
array(
'eventDisplay'=>'upcoming',
//'posts_per_page'=>10,
)
);
$count = 1;
foreach($all_events as $post) {
setup_postdata($post);
?>
<div class="col-sm-3">
<span class="event-date"><?php echo tribe_get_start_date($post->ID, true, 'j M'); ?></span>
<h3><?php the_title(); ?></h3>
<?php if ( has_post_thumbnail() ) { ?>
<div class="event-thumb">
<?php the_post_thumbnail('thumbnail'); ?>
</div>
<div class="event-excerpt">
<?php the_excerpt(); ?>
</div>
<?php } else { ?>
<div class="event-content">
<?php the_content(); ?>
</div>
<?php } ?>
</div>
<?php
if($count == 4){
echo "<div class='seperator'></div>";
$count =1;
}
?>
<?php $count++; } //endforeach ?>
<?php wp_reset_query(); ?>
I'd actually solve this 100% in CSS, so you don't need any counting or handling inside your PHP code.
Have a look at this JSFiddle.
float: left will cause the single elements to all follow each other (left aligned).
clear: left on every 4 * n + 1-th element (nth-child(4n+1)) will clear this, essentially forcing a line break.
There is one caveat to this: If there's no room for all 4 entries in one row, you'll end up with additional wrapping, which can be avoided by defining a fixed width for the container.
A simplified in-code version for PHP would just count the fields written and add a line break as necessary:
$i = 1; // counter
foreach ($events as $event) { // iterate over all events
if ($i++ % 4 == 0) // a % b will be 0 for 4, 8, etc.
echo '<br />'; // print the line break using whatever HTML you see fit.
print_event($event); // print the actual event
}
You might ask whether I check for the line break before actually printing an event: That's to prevent additional line breaks if the number of entries is a multiple of 4, i.e. I avoid having an empty trailing line.
You need the modulo operator. It works like this:
$i == 0;
foreach($some_array as $some_value){
if ($i % $number_to_divide_by == 0) {
// do something here every nth time
}
$i++;
}
I am attempting to make a sortable list out of list items populated from the database using the jQuery plug in but the effect is only applied to the first item presented:
<?php if(isset($bookmarks)) : foreach($bookmarks as $row) :?>
<div id="makeDrag">
<?php $fixed = preg_replace('#^[^:/.]*[:/]+#i', '', $row->URL); ?>
<li>
<div class="well">
<div><?php echo anchor('http://'.$fixed, $row->Name); ?></div>
<div><strong>Comments:</strong> <?php echo $row->Comments; ?></div>
<h4 class="btn-small">
<?php echo anchor("site/delete/$row->id", "Delete"); ?>
</h4>
</li>
</div>
<?php endforeach; ?>
I can kind of see where this is going wrong but do not know how to fix it. I would obviously like the effect to affect all the populated li not just the first one. Any help would be great. Sorry if I am unclear, I can try and rephrase things if this is confusing.
The cause is likely because you have
$('#makeDrag').sortable();
but you also have a foreach statement that creates multiple #makeDrag elements thus making your HTML invalid.
To fix this:
<?php if(isset($bookmarks)) : ?>
<ul id="makeDrag">
<?php foreach($bookmarks as $row) : ?>
<?php $fixed = preg_replace('#^[^:/.]*[:/]+#i', '', $row->URL); ?>
<li>
<div class="well">
<div><?php echo anchor('http://'.$fixed, $row->Name); ?></div>
<div><strong>Comments:</strong> <?php echo $row->Comments; ?></div>
<h4 class="btn-small"><?php echo anchor("site/delete/$row->id", "Delete"); ?></h4>
</div>
</li>
<? endforeach; ?>
</ul>
<?php endif; ?>
HTH
I would like to output some specific HTML on the third iteration of a loop in PHP. Here is my code:
<?php foreach ($imgArray as $row): ?>
<div class="img_grid"><?= $row ?></div>
<?php endforeach; ?>
On the third iteration of this loop, Instead of displaying:
<div class="img_grid"><?= $row ?></div>
I would like to display:
<div class="img_grid_3"><?= $row ?></div>
I would like to end up with this if my array looped 8 times:
<div class="img_grid">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid_3">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid_3">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid">[some html]</div>
Thanks
Assuming $imgArray is an array and not an associative array (i.e. it has numeric indices), this is what you want:
<?php foreach($imgArray as $idx => $row): ?>
<?php if($idx % 3 == 2): ?>
<div class="img_grid_3"><?php echo $row; ?></div>
<?php else: ?>
<div class="img_grid"><?php echo $row; ?></div>
<?php endif; ?>
<?php endforeach; ?>
You could tighten it up a bit like this:
<?php foreach($imgArray as $idx => $row):
if($idx % 3 == 2) {
$css_class = 'img_grid_3';
} else {
$css_class = 'img_grid';
}
?>
<div class="<?php echo $css_class; ?>"><?php echo $row; ?></div>
<?php endforeach; ?>
Or even more (some folks would just go with a ternary conditional inline in the HTML), but the law of diminishing returns kicks in eventually with regard to readability. Hopefully this gives you the right idea, though.