I'm working on this code and trying to get it to only pull 4 entries from the repository and it keeps pulling all of my entries.
<?php
while ( $i < 4) {
foreach ($churchEvents->getResults() as $churchEvent){
?>
<tbody>
<tr>
<td> <?php echo $churchEvent->getStructuredText('church-events.event-title')->asText(); ?>
</td>
<td class="cuntd" style="vertical-align: middle;">
<?php echo $churchEvent->getDate('church-events.event-start-date')->asDateTime()->format('l, F j, Y'); ?>
</td>
</tr>
</tbody>
<?php $i++; } } ?>
You have two loops, but there is no reason to have two. The inner one (foreach) already iterates through all the $churchEvents, so the outer one (while) will not make it do less.
Remove the outer while loop and the $i++;, and make the inner loop only loop over the first four elements.
For this, you can use the => syntax in the foreach statement to get the value of $i, and then add an if to exit the loop:
<tbody>
<?php
foreach ($churchEvents->getResults() as $i => $churchEvent){
if ($i >= 4) break;
?>
<tr>
<td> <?= $churchEvent->getStructuredText('church-events.event-title')->asText() ?>
</td>
<td class="cuntd" style="vertical-align: middle;">
<?= $churchEvent->getDate('church-events.event-start-date')->asDateTime()->format('l, F j, Y') ?>
</td>
</tr>
<?php
}
?>
</tbody>
Note that tbody should not be generated more than once, so it should stay out of the loop.
Because while is outside foreach.
while ( $i < 4) {
foreach ($churchEvents->getResults() as $churchEvent){
At the start of foreach try if combine with break.
//you don't need while here anymore
foreach ($churchEvents->getResults() as $churchEvent){
if ($i >= 4) {
break;
}
The method names are distinctive enough to make a guess what library/api you're using: (http://prismicio.github.io/php-kit/namespaces/Prismic.html), right?
The ->getResults() method returns an array. So, there are several options; here are some of them:
Using an SPL LimitIterator:
<?php
// only fetching the first four entires
$iter = new LimitIterator( new ArrayIterator($churchEvents->getResults()), 0, 4);
foreach ($iter as $churchEvent) { ?>
<tbody>
<tr>
<td> <?php echo $churchEvent->getStructuredText('church-events.event-title')->asText(); ?></td>
<td class="cuntd" style="vertical-align: middle;"><?php echo $churchEvent->getDate('church-events.event-start-date')->asDateTime()->format('l, F j, Y'); ?></td>
</tr>
</tbody>
<?php
}
Using array_slice() to get the first four elements and then iterate over those four:
<?php
// copying the first four element of the array
$arr = array_slice($churchEvents->getResults(), 0, 4);
foreach ($arr as $churchEvent) { ?>
<tbody>
<tr>
<td> <?php echo $churchEvent->getStructuredText('church-events.event-title')->asText(); ?></td>
<td class="cuntd" style="vertical-align: middle;"><?php echo $churchEvent->getDate('church-events.event-start-date')->asDateTime()->format('l, F j, Y'); ?></td>
</tr>
</tbody>
<?php
}
(prefered option:) Only request four items/fragements:
I'm not familiar with the api but at the very least there's the method pageSize(integer $pageSize) : \Prismic\SearchForm which sets the resultset size for the pagination. Maybe you can even limit the number of results in the response with some predicates or a limit-clause or something, i.e. only request what you really need.
Related
How can I make this foreach line only go through the first result?
<?php foreach ($collection as $product) : ?>
I tried the following, but that does not work. It than does not display any results:
<?php foreach (array_slice($collection, 0, 1) as $product) : ?>
EDIT:
The following works perfect:
<?php
$i = 0;
foreach ($collection as $product) :
if($i < 1) {
Inner content
}
$i++;
endforeach;
?>
Total current code:
<tbody>
<tr>
<td class="image" rowspan="3">
<?php $i = 0; foreach ($collection as $product) : if($i < 1) {?>
<img src="<?php echo $this->helper('catalog/image')->init($product, 'thumbnail')->resize(75) ?>" alt="<?php echo $this->htmlEscape($product->getName()) ?>" width="75" height="75" />
<?php } $i++; endforeach ?>
</td>
<td class="order" colspan="2">order</td>
<td class="exclTax">excl. vat</td>
<td class="inclTax">incl. vat</td>
</tr>
<?php foreach ($collection as $product) : ?>
<tr>
<td class="select"><input type="radio" name="featured_1807" id="featured_1807_1349567899" value="3071895, IM" data-product-id="3071895" data-product-sup="IM"></td>
<td class="title"><?php echo $this->htmlEscape($product->getName()) ?></td>
<td class="price"><?php echo $abstractBlock->getPriceHtml($product, true, '-related') ?></td>
<td class="priceIncl"><?php echo $abstractBlock->getPriceHtml($product, true, '-related') ?></td>
</tr>
<?php endforeach ?>
</tbody>
How can I achieve that?
Why bother with a loop if you are only interested in the first occurance of $collection
You could do this instead and probably not have to change any code you currently have inside your loop
<?php
$product = $collection[0];
Code you had in the loop
?>
If its not a numeric key then you can use
<?php
reset($collection); // make sure you are on first occ
$product = $collection[key($collection)];
... html stuff
// and then do again for your second loop
// if you only want the first occ of that as well
reset($collection); // make sure you are on first occ
$product = $collection[key($collection)];
reset($collection); // Resets the array's internal pointer to the first element
$product = current($collection); // Returns the current element which is now first element
As far as I'm concerned, this is the best solution I would ever go for if I need to only extract the first element from an array.
I got a foreach which loops through my database for each user.
<?php
foreach($users as $user) {
?>
<tr>
<td>
<?php
for ($i=1; $i < 52; $i++) {
echo $i;
}
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
This loop through database and echos the username, now I tried to build a for loop inside this so that every user has a number, I took as an example a very basic for loop ( it will be changed later).
The problem is that I get all numbers printed out for each user, but I just want to print out the number once for a user. How do I solve this.
If you want unique index number for user, you do not need extra loop.
Just add an increment variable:
And increment it in existing loop.
<?php
$i=0;
foreach($users as $user) {
++$i; // For printing first user, it will be 1 not 0.
// Therefore, increment is placed before printing name.
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php
}
?>
This should be enough to achieve what you're trying to do :
Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it.
Also you should avoid to open your php tags ten thousands times for a better visibility into your code :)
<?php
$i = 0;
foreach($users as $user) {
$i++;
echo'<tr>
<td>'.$i.'</td>
<td>'.$user['firstname'].'</td>
</tr>';
?>
<?php
$i=1;
foreach($users as $user) {
?>
<tr>
<td>
<?php
echo $i++;
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
Try to use the key in foreach
<?php foreach ($users as $key => $user) : ?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php endforeach; ?>
I have a small invoice web tool.
So I would like to find out the total amount of all positions of items and if it reached a maximum level it should print the following positions on the second page of the invoice.
I use the sample code to "design" my invoices:
http://codepen.io/rafaelcastrocouto/pen/LFAes/
My idea is: first count all characters of the foreach loop.
But I don't know how I should continue?
Please give me some hints. Thanks
EDIT: here is my foreach loop code:
<?php foreach( $items as $it): ?>
<tr class="even">
<td style="width:8%;"><?php echo $pos; ?></td>
<td style="width:47%;"><?php
$string = $it->invoice_item_text;
if (strlen($string) > 350) $string = substr($string,0,350).'...';
echo $string;
?></td>
<td style="width:15%;">
<?php if ($it->invoice_item_type == 3) {$date = date('M Y', strtotime($it->invoice_item_date)); } else { $date = date('d.m.Y', strtotime($it->invoice_item_date)); } ?>
<?php echo $date; ?>
</td>
<td style="width:20%;"><?php if ($it->invoice_item_time != '0') { if ($it->invoice_item_type == 1 or $it->invoice_item_type == 2) echo gmdate('H:i', $it->invoice_item_time);}; ?></td>
<td style="width:10%;"><?php echo number_format($it->invoice_item_sum, 2, ',', ' '); ?> €</td>
</tr>
<?php $pos++; ?
<?php endforeach; ?>
Use php Array as session variable
$_SESSION['items'] = $items;
if you store value in session you can use this value any page
Here's the code from my
Controller Page
public function table1(){
$this->load->model('test_model');
$data['value']= $this->test_model->getAlltable1();
$data['value2']= $this->test_model->getAlltable0();
$this->load->view('table1', $data);
}
Views Page
<table class="table">
<tbody>
<?php foreach ($value as $v){ ?>
<?php foreach ($value2 as $v2){ ?> //different table
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$v2->tech_voc)?></td>
</tr>
<?php } ?>
<?php } ?>
The output is somewhat like this
1 .75
1 .75
1 .75
1 .75
What I want to display is something like this
1 .75
What happen here is that, instead it multiply once, it all multiply each row. And I think it is because I put foreach inside a foreach Please help me.
EDIT
Oh yeah, I already tried deleting the foreach value2
but it says v2 is undefined variable
HOPE it helps.
NEW EDIT:---------------------------------------
If you're trying to multiply where the keys are the same ($value[0]*$value2[0], $value[1]*$value2[1], etc) try this.
<?php
$col1_sum = 0;
$col2_sum = 0;
foreach ($value as $k => $v){ ?>
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$value2[$k]->tech_voc)?></td>
<?php //update sums
$col1_sum += $v->tech_voc;
$col2_sum += ($v->tech_voc*$value2[$k]->tech_voc);
?>
</tr>
<?php } ?>
<!-- row with sums -->
<tr>
<td><?php echo $col1_sum?></td>
<td><?php echo $col2_sum?></td>
</tr>
Edited based on comments/chat to include a sum row.
I have retrieved some values from database. In my view file I have the following:
$row['fee_amount'];
Now, I want to sum up all the values inside $row['fee_amount']; and then show it.
I know I could sum up when querying the database, but I am interested to learn how to add using PHP .
Would you please kindly teach me how to do it?
EDIT
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>S.N</th>
<th>Fee Type</th>
<th>Fee Amount</th>
</tr>
</thead>
<tbody>
<?php $i = 0; foreach ($records as $row){ $i++; ?>
<tr>
<td><?php echo $i; ?>.</td>
<td><?php echo $row['fee_type'];?></td>
<td><?php echo $row['fee_amount'];?></td>
</tr>
<?php } ?>
</tbody>
<tr>
<td></td>
<td>Total</td>
<td>
I WANT TO DISPLAY THE SUMMATION RESULT HERE ADDING UP VALUES INSIDE THIS>>> <? $row['fee_amount']; ?>
</td>
</tr>
</table>
<?php } ?>
In your view file, with your foreach loop, add a $sum variable next to your $i counter and add the amount per each iteration (similar to like you increase $i):
<?php
$i = 0;
$sum = 0;
foreach ($records as $row)
{
$i++;
$sum += $row['fee_amount']; ?>
(I put this over multiple lines to make it more readable).
After the foreach has finished, $sum contains the total amount:
<td>Total: <?php echo $sum; ?></td>
That simple it is. You only need a new variable ($sum) and do the calculation.
Use a loop
$sum = 0;
while($row...){
$sum += $row['fee_amount']
}
echo $sum;
You could use;
$someValue = 0;
foreach($row["fee_amount"] as $value) {
$someValue = $someValue + $value;
}
using this php function, if $row['fee_amount'] is an array ^_^
for example:
$a = array(2, 4, 6, 8);
array_sum($a)