I am trying to get a sum in my variable session basket (it is a multiple array), I want to sum the elements that represent the cost of product.
Page where I add elements into the basket
<?php
session_start();
include('link.php');
if(!isset($_SESSION['basket'])){
$_SESSION['basket']=[];
}
// $id_permit=$_POST['id_fp'];
// $chosen_date=$_POST['date_permit'];
$_SESSION['little_basket']= array (
'itemIdPermit'=> "'".$_POST["id_fp"]."'",
'itemChosenDate'=> "'".$_POST["date_permit"]."'",
'itemFinalPrice'=> "'".$_POST["final_price"]."'",
'itemFinalPriceNotDiscount'=>"'".$_POST["price_not_discount"]."'"
);
// $_SESSION['basket'][] = $_SESSION['little_basket'];
array_push($_SESSION['basket'], $_SESSION['little_basket']);
print_r($_SESSION['basket']);
// $_SESSION['basket']=[];
// echo $_SESSION['basket'];
// header('location:index.php?area=fishing_permit');
?>
Page where I show the contents of the basket
<?php
// session_start();
// include('link.php');
// include('add_basket.php');
// $ids = '';
/* foreach($_SESSION['basket'] as $id){
$ids = $ids . $id . ",";
};*/
$lista_de_items_no_carrinho = $_SESSION['basket'];
?>
<ul id="list_product">
<?php
$basketLength=count($lista_de_items_no_carrinho);
for($i=0;$i< $basketLength;$i++){
$sqlListChosenPermits = "select * from type_of_permits
where id_type_of_permit =".$lista_de_items_no_carrinho[$i]['itemIdPermit'];
$outcomeListChosenPermits = $link->query($sqlListChosenPermits);
$line = mysqli_fetch_assoc($outcomeListChosenPermits);
?>
<li>
<div class="box_info"><h4><?php echo utf8_encode($line['type']); ?></h4><br>Validity: <?php echo utf8_encode($line['validity']);?> - Price: €<?php echo utf8_encode($line['price_eur']); ?> </div>
<div class="map">Map info</div>
<div class="rules">Rules</div>
<div class="permit_facsimile">Permit facsimile</div>
<div class="chosen_date"><?php echo trim ($lista_de_items_no_carrinho[$i]['itemChosenDate'], "'") ;?></div>
<div class="price">Euro <?php
$var= trim ($lista_de_items_no_carrinho[$i]['itemFinalPrice'],"'");
if (!empty($var) ){
echo ($var);
} else {
echo trim($lista_de_items_no_carrinho[$i]['itemFinalPriceNotDiscount'],"'");
} ?></div>
<div class="add_basket"><i class="fa fa-shopping-cart"></i>Remove from the Basket</div>
<input type="hidden" name="last_price" id="last_price" value="<?php
if (!empty($lista_de_items_no_carrinho[$i]['itemFinalPrice'])) {
echo trim ($lista_de_items_no_carrinho[$i]['itemFinalPrice'],"'");
} else {
echo trim($lista_de_items_no_carrinho[$i]['itemFinalPriceNotDiscount'],"'");
} ?>">
</li>
<?php
}
?>
</ul>
<p>Total price:<span class="total_price"><?php
$lista_de_items_no_carrinho = $_SESSION['basket'];
$listaPrice=$lista_de_items_no_carrinho[$i]['itemFinalPriceNotDiscount'];
$basketLength=count($listaPrice);
$sum=0;
for($k= 0; $k < $basketLength; $k++){
$sum += ($basketLength[$k]);
echo ($sum);
}?>
</span></p>
<div class="buying"><button type="submit"><i class="fa fa-shopping-cart"></i>Conclude the purchase</button></div>
</div>
I would like to sum the numerics value of 'ItemFinalPrice' and 'ItemFinalPriceNotDiscount'.
Thanks in advance.
Fanjo
You should take a look at array_column and array_sum:
$finalPriceSum = array_sum(array_column($basket, 'itemFinalPrice'));
$finalPriceNoDiscountSum = array_sum(array_column($basket, 'itemFinalPriceNotDiscount'));
Related
I have the following data and would like to display it in different containers in html.
Name Price Difference Signal
CA.PA 15.85 3.5609257364073 MACD
AZN.ST 896 3.4881049471963 MACD
AMGN 258.57 1.6391533819031 SMA 50/200
The containers are winner_1. As of right now the first winner_1 display the last Name from the above table.
How can I get it to say CA.PA in the first winner_1, and AZN.ST in the second winner_1, and AMGN in the last winner_1.
<div class="overview">
<h1>Winners</h1>
<div class="winner">
<?php
foreach ($res_winners_weekly as $r){
$name = $r["Name"];
$Price = $r['Price'];
$percent_diff = $r['Difference'];
$signal = $r['Signal'];
}
?>
<div class="winner_1">
<?php echo $name; ?>
</div>
<div class="winner_1">
<?php echo $name +1; ?>
</div>
<div class="winner_1">
</div>
</div>
</div>
The page can be seen here:
https://signal-invest.com/markets-today/
One option is generated div tags using php:
<div class="overview">
<h1>Winners</h1>
<div class="winner">
<?php
foreach ($res_winners_weekly as $r) {
$name = $r["Name"];
$Price = $r['Price'];
$percent_diff = $r['Difference'];
$signal = $r['Signal'];
echo "<div class='winner_1'>";
echo "<a href='#'>{$name}</a>";
echo "</div>";
}
?>
</div>
</div>
You should see following logic and try doing this way. Hopefully your problem will be resolved.
<div class = "overview">
<h1>Winners</h1>
<div class = "winner">
<?php
foreach ($res_winners_weekly as $r) {
$name = $r["Name"];
$Price = $r['Price'];
$percent_diff = $r['Difference'];
$signal = $r['Signal'];
echo "<div class='winner_1'><a href='#'> $name </a></div>";
}
?>
</div>
</div>
I need to wrap every 2 divs with another div for a project (a row) so it will look like:
<div class="row">
<div> Item </div>
<div> Item </div>
</div>
<div class="row">
<div> Item </div>
<div> Item </div>
</div>
I have tried a few solutions but they dont work since the items coming in are odd (9 items). Here is what I had:
<?php
$count = 0;
foreach ($contents as $content)
{
//var_dump($content);
$books = $content["tags"];
$book_image = $content['content_image'];
$book_desc = $content['content_social_description'];
++$count;
if($count == 1)
{
echo "<div class='et_pb_row'>";
}
foreach ($books as $book)
{
$book_name = $book['tag_name'];
$book_name_trim = str_replace(' ', '-', $book_name);
?>
<!-- Inside the Book Loop -->
<div class='et_pb_column et_pb_column_1_2 books' style="background: url('https://s3-us-west-2.amazonaws.com/crowdhubproverbs31/<?php echo $book_image ;?>');">
<h2><?php echo $book_name; ?></h2>
<p><?php echo $book_desc; ?></p>
<?php echo $count; ?>
</div>
<?php
}
if ($count == 2)
{
echo "</div>";
$count = 0;
}
}
?>
This works except the second to last row has 3 items even though it dispays the "count" as 2 when I echo it out so it should reset but doesnt. So its:
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
You should open and close your <rows/> in the books loop, and add a late check for odd books:
<?php
$count = 0;
foreach ($contents as $content)
{
//var_dump($content);
$books = $content["tags"];
$book_image = $content['content_image'];
$book_desc = $content['content_social_description'];
foreach ($books as $book)
{
++$count;
if($count == 1)
{
echo "<div class='et_pb_row'>";
}
$book_name = $book['tag_name'];
$book_name_trim = str_replace(' ', '-', $book_name);
?>
<!-- Inside the Book Loop -->
<div class='et_pb_column et_pb_column_1_2 books' style="background: url('https://s3-us-west-2.amazonaws.com/crowdhubproverbs31/<?php echo $book_image ;?>');">
<h2><?php echo $book_name; ?></h2>
<p><?php echo $book_desc; ?></p>
<?php echo $count; ?>
</div>
<?php
if ($count == 2)
{
echo "</div>";
$count = 0;
}
}
}
if ($count > 0)
{
echo "</div>";
}
?>
Doing so, your $count variable will be incremented only when foreach($books AS $book) loop is run (thus you have at least one book to print)
You can take advantage of array_chunk :
//First make a generator to get all books
function allBooks($contents) {
foreach($contents as $content) {
foreach($content['tags'] as $book) {
yield $book; //Here you can yield whatever you want !
}
}
}
//Then create rows
$itemPerRow = 2;
$rows = array_chunk(iterator_to_array(allBooks($contents)), $itemPerRow, true);
//Display all
foreach($rows as $row) {
echo '<row>';
foreach($row as $book) {
//Display the book !
}
echo '</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++;
I have set-up a news page which retrieves news from MYSQL news table.
I am trying to identify if the news column is odd or even, so if the news columns is odd or even it will add a class to the div element.
My code is as follows:
<?php
$cat = $_GET['cat'];
$date = $_GET['date'];
if ($date !="") {
$date = explode('-', $date);
$year = $date[1];
$month = $date[0];
$month = date("m", strtotime($month));
$sql = "SELECT * FROM news WHERE year(newsDate) = '$year' AND month(newsDate) = '$month' AND newsState = 1 ORDER BY newsDate DESC";
} else {
$sql = "SELECT * FROM news WHERE newsState = 1 ORDER BY newsDate DESC";
}
$result = $conn->query($sql);
$rows = $result->num_rows;
$pager = new PS_Pagination($conn, $sql, 5, 10, null);
$rs = $pager->paginate();
$num = $rs->num_rows;
if($num >= 1 ){
while($row = $rs->fetch_assoc()){
?>
<div class="news <?php echo $num; ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php } } else {
echo "No records found!";
}
if ($rows >= 5) {
echo "<div class='page-nav blog-nav'>";
echo $pager->renderFullNav();
echo "</div>";
}
?>
TAke any flag which maintains odd-even position...
$f = 0; //ADDED THIS LINE
if($num >= 1 ){
while($row = $rs->fetch_assoc()){
if($f%2==0) //ADDED THIS LINE
$class_name = "even"; //ADDED THIS LINE
else //ADDED THIS LINE
$class_name = "odd"; //ADDED THIS LINE
?>
<div class="news <?php echo $class_name; ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php $f++; } } else {
echo "No records found!";
}
if($num >= 1 ){
$tr = 1;
while($row = $rs->fetch_assoc()){
if($tr%2 == 0)
{
//then even class
}
else
{
//odd class
}
?>
<div class="news <?php echo $num; ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php $tr++; } } else {
echo "No records found!";
}
Use counter variable and check if it is even or odd ?
Create variable, increment that in each loop and check, if $i % 2 is 0 (even) or 1 (odd).
$i = 1;
while($row = $rs->fetch_assoc()){
?>
<div class="news <?php echo $num; echo $i % 2 == 0 ? ' even' : ' odd' ?>">
<div class="four columns">
<p><img src="/news-images/thumbs/thumb_<?php echo $row['newsImage1']; ?>" alt=""/></p>
</div>
<div class="eight columns">
<h3><?php echo $row['newsTitle']; ?></h3>
<p><?php echo stripslashes(strip_tags($row['newsDescription'])); ?></p>
</div>
</div>
<?php
$i++;
}
Take $classname = '';
Get news ID in loop and divide / 2 and compare whether you getting odd / even value. In case odd value add $classname = 'oddCLASS' and in case even value add $classname = 'evenCLASS' and updare class = $classname wherever you required.
This way it will automatically update dynamic class.
so the fastest way to do this is just by using a boolean:
$odd = false;
while ( .... )
{
echo ($odd = !$odd) ? 'odd' : 'even';
}
No need to keep a counter for that, no need for a modulo and it keeps the code pretty clean. My preferred way unless you need to keep a counter. And even then: $counter & 1 == 1 is faster than $counter % 2 == 1 and does exactly the same.
Simple explanation:
echo ($odd = !$odd) ? 'odd' : 'even';
// will become
$odd = ! $odd; // it flips the boolean
if ($odd)
echo 'odd';
else
echo 'even';
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.