Count and sum values from array in PHP - php

I have a page that show my orders in day, but now i want to count and sum the values from 7 / 15 and 30 days ago (if possible in list), or just count/sum in this step: <strong>Soon</strong>
$pedido->valor_pedido is my value from order
$pedido->id its id from order, i use to count.
My code:
<div class="row">
<?php
$totalPedido = 0;
$contagPedido = 0;
foreach ($pedidos as $pedido) {
$totalPedido += $pedido->valor_pedido; // sum day orders
$contagPedido += count($pedido->id); //count day orders
}
?>
<div class="span12">
<!-- Widgets -->
<ul class="widgets">
<!-- Basic widget item -->
<li class="span3">
<span class="widget-label"><span class="awe-star"></span> This Week</span>
<strong>Soon</strong>
</li>
<!-- /Basic widget item -->
<!-- Clickable widget item -->
<li class="span3">
<span class="widget-label"><span class="awe-star"></span> Totay</span>
<strong>R$ <?= ConverteReal($totalPedido) ?></strong>
</li>
<!-- /Clickable widget item -->
<!-- Widgets with graphs -->
<li class="span3">
<span class="widget-label"><span class="awe-star"></span> Orders this week</span>
<strong>Soon</strong>
</li>
<li class="span3">
<span class="widget-label"><span class="awe-star"></span> Orders today</span>
<strong><?= $contagPedido ?></strong>
</li>
<!-- /Widgets with graphs -->
</ul>
<!-- /Widgets -->
</div>
</div>

According to PHP Manual, count() will use to get the count of all elements in an array
If $pedido->id is a unique ID, you can just get the count of $pedidos array like
<?
$contagPedido = count($pedidos); // total no of orders
foreach ($pedidos as $pedido) {
$totalPedido += $pedido->valor_pedido; // sum day orders
}
?>

Related

is there a way to calculate total earnings without repetition of amount from results

i have this code that calculate the total amount from a row. the solution adds up instead of printing only the expected results. for example 35,35 will give a result like 35,70 instead of printing only 70. the variable $stmt is associated to a query.
<?php
$netTotal = 0;
foreach ($stmt as $val) {
?>
<?php $t = $val['PAY_AMOUNT'] - (($val['PAY_AMOUNT']) * 0.1);
$Total += $t;
?>
<div class="col">
<h2 class="card-title font-size-40"><?php echo $Total; ?></h2>
<p class="card-sub font-size-18 line-height-24">Total Earnings</p>
</div><?php } ?>
<div class="col-auto font-size-60">
<i class="la la-money text-primary"></i>
</div>
</div><!-- end row -->
</div><!-- end card-content -->

two nested foreach

I have 2 tables in database first one is $slide_images and second is $why_us and I am using owl carousel for images.
The $slide_images contains 10 rows.
The $why_us contains 3 rows.
I need each image take one row of $why_us that's mean the first 3 images will have a text from $why_us table.
I tried many ways to do that but it's not given me what I want and I can't edit tables to do that and the id column is not nested to join them with SQL.
Can i solve them with nested foreach?
<div class="home_area">
<!-- start Carousel -->
<div class="owl-carousel block_1">
<?php
if(is_array($slide_image)){
foreach($slide_image as $src){
?>
<div class="overlay-text">
<div class="carousel_item" style="background-image:url('<?php echo base_url(); echo $src->url; ?>');"></div>
<div class="text-layer">
<!--============ start we us ================ -->
<?php if($why_us != ''){ ?>
<div class="we">
<div class="container">
<div class="row">
<?php foreach($why_us as $we){ ?>
<div class="box">
<h6><?php echo $we->name; ?></h6>
<div class="text"><?php echo $we->desc; ?></div>
</div>
<?php }?>
</div>
</div>
</div>
<?php } ?>
<!--============= end we us ========== -->
</div>
</div>
<?php } }?>
</div>
<!-- end Carousel -->
</div>
I hope I described my question well.
You should not use nested loops. That creates a cross product between the arrays.
Instead, you should just have one loop that uses the corresponding elements of both arrays. Since one of the arrays is smaller, you should check that the index exists.
foreach ($slide_image as $index => $src) {
// code that uses `$src` here
if (isset($why_us[$index])) {
$we = $why_us[$index];
// code that uses $we here
}
}

Tab contents with ACF Nested Repeater

I have a nested ACF repeater:
section_container (parent repeater)
section_heading (text field) sub_section_container (sub repeater)
sub_section_heading (text field) food_item (sub sub repeater)
item_name (text) item_description (text) price (text)
All of which needs to be wrapped in div Section_01 this will then appear in the first "tab" section contents, with the tab heading taken from the text field "section_heading". Section headings will be things like, Starters / Mains / Sweets / Drinks
If the user adds a row in the back end "section_container" this repeats all of the above, but this needs to be wrapped in a div called Section_02 in order for it to be displayed in the next tab. This is achieved via a counter - as I don't want a pre determined number of sections / rows.
At the moment rather than ALL of the content from parent repeater "section_container" being displayed within a single div, it's taking each single array output and then wrapping that content in a div.
What I get is:
<div class="section_01">
Starter item 1 Start Price 1 Starter Description 1
</div>
<div class="section_02">
Starter item 2 Start Price 2 Starter Description 2
</div>
What I want is:
<div class="section_01">
Starter item 1 Start Price 1 Starter Description 1
Starter item 2 Start Price 2 Starter Description 2
</div>
<div class="section_02">
Mains item 1 Mains Price 1 Mains Description 1
Mains item 2 Mains Price 2 Mains Description 2
</div>
<?php
/**
* Template part for displaying the food menu
*
* #package GL_Apollo
*/
?>
<script>
function openSection(evt, sectionName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(sectionName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
<div class="food-menu-container">
<div class="menu-title"><?php the_field('menu_title'); ?> </div>
<!-- Tab links -->
<div class="food-menu-tab-container">
<div class="tab">
<?php
$counter_tab = 1;
if( have_rows('section_container') ) :
while( have_rows('section_container') ): the_row();
$section_name = array( get_sub_field('section_heading') );
foreach ($section_name as $section_names) {?>
<button class="tablinks" onclick="openSection(event, 'section_0<?php echo $counter_tab; ?>')">
<?php echo $section_names; ?>
</button>
<?php $counter_tab++; // increment before foreach ends
}
endwhile;
endif;
wp_reset_postdata();
?>
</div>
</div>
<!-- Food content -->
<div class="menu-section-container">
<?php
$counter = 1;
// check if the repeater field has rows of data
if( have_rows('section_container') ):
// loop through the rows of data
while ( have_rows('section_container') ) : the_row();
if( have_rows('sub_section_container') ):
// loop through the rows of data
while ( have_rows('sub_section_container') ) : the_row();
$sub_head = get_sub_field('sub_section_heading');
if( have_rows('food_item') ):
// loop through the rows of data
while ( have_rows('food_item') ) : the_row();
$item = get_sub_field('item_name');
$price = get_sub_field('price');
$description = get_sub_field('item_description');
$menu_content = array (
"<div class='sub_head'>$sub_head</div>" . "<div class='item'>$item</div>" . "<div class='price'>$price</div>" . "<div class='description'>$description</div>"
);
foreach ($menu_content as $menu_contents); { ?>
<div id="section_0<?php echo $counter; ?>" class="tabcontent">
<?php echo $menu_contents ; ?>
</div>
<?php $counter++; // increment before foreach ends
}
endwhile;
endif;
endwhile;
endif;
endwhile;
endif;
echo '<pre>';
var_dump( $menu_contents );
echo '</pre>';
?>
</div> <!-- section -->
</div> <!-- menu-section-container -->
<span class="btn" data-glf-cuid="0c1de6b2-1ca9-4202-b790-3cd5a62af2b3" data-glf-ruid="9e6118c3-d144-4511-973e-d7d7f7418e1a" ><?php the_field('order_button'); ?></span>
<script src="https://www.fbgcdn.com/widget/js/ewm2.js" deferasync ></script>
</div> <!-- food-menu-container -->
Forgive me for trying to understand the question however, is it simply the case you're wanting to wrap a div around each food item section rather than each food item?
If this is the case, you can add a div between the if and while statements for the food_item.
<?php $foodItem == 1; ?>
<?php if( have_rows('food_item') ): ?>
<div class="section_<?php echo $foodItem; ?>">
<?php while( have_rows('food_item') ): the_row(); ?>
<?php the_field('item_name'); ?>
<?php the_field('item_description'); ?>
<?php the_field('price'); ?>
<?php $foodItem++; ?>
<?php endwhile; ?>
</div>
<?php endif; ?>
This should give you the outcome of:
<div class="section_1">
Starter item 1 Start Price 1 Starter Description 1
Starter item 2 Start Price 2 Starter Description 2
</div>
<div class="section_2">
Starter item 1 Start Price 1 Starter Description 1
Starter item 2 Start Price 2 Starter Description 2
</div>
If I have missed something, let me know.
M. Ferguson is correct in what he says, however the tabs section could also do with some cleaning up. Here is the complete cleaned up code. This should work if it does not let me know.
<script>
function openSection(evt, sectionName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(sectionName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
<div class="food-menu-container">
<div class="menu-title"><?php the_field('menu_title'); ?> </div>
<!--Menu Tabs-->
<div class="food-menu-tab-container">
<?php $tabNumber = 1;
if( have_rows('section_container') ) :
<div class="tab">
while( have_rows('section_container') ): the_row();
$section_name = get_sub_field('section_heading');?>
<button class="tablinks" onclick="openSection(event, 'section_0<?php echo $tabNumber; ?>')">
<?php echo $section_name; ?>
</button>
<?php $counter_tab++;
endwhile;?>
</div>
<?php endif;?>
</div>
</div>
<div class="menu-section-container">
<!--Food Menu-->
<?php $foodItem = 1; ?>
<?php if( have_rows('food_item') ): ?>
<div class="section_0<?php echo $foodItem; ?> section">
<?php while( have_rows('food_item') ): the_row(); ?>
<!--Add styling: .section .section_inner > div {display:inline-block;}-->
<div class="section_inner_0<?php echo $foodItem; ?> section_inner">
<div class="sub_head"><?php get_sub_field('sub_section_heading');?> </div>
<div class="item"><?php the_field('item_name'); ?> </div>
<div class="price"><?php the_field('item_description'); ?> </div>
<div class="description"><?php the_field('price'); ?></div>
<?php $foodItem++; ?>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
</div>
</div>
<span class="btn" data-glf-cuid="0c1de6b2-1ca9-4202-b790-3cd5a62af2b3" data-glf-ruid="9e6118c3-d144-4511-973e-d7d7f7418e1a" ><?php the_field('order_button'); ?></span>
<script src="https://www.fbgcdn.com/widget/js/ewm2.js" deferasync ></script>
Outcome HTML:
<div class="section_01">
<div class="section_inner_01 section_inner">
<div class="sub_head">Starter </div><div class="item">item 1 </div><div class="item_price">Start Price 1 </div><div class="description">Starter Description 1</div>
</div>
<div class="section_inner_01 section_inner">
<div class="sub_head">Starter </div><div class="item">item 2 </div><div class="item_price">Start Price 2 </div><div class="description">Starter Description 2</div>
</div>
</div>
<div class="section_02">
<div class="section_inner_02 section_inner">
<div class="sub_head">Starter </div><div class="item">item 1 </div><div class="item_price">Start Price 1 </div><div class="description">Starter Description 1</div>
</div>
<div class="section_inner_02 section_inner">
<div class="sub_head">Starter </div><div class="item">item 2 </div><div class="item_price">Start Price 2 </div><div class="description">Starter Description 2</div>
</div>
</div>
Outcome Front End:
Starter item 1 Start Price 1 Starter Description 1
Starter item 2 Start Price 2 Starter Description 2

Count total items within two loops - loop within loop

Project: WordPress project
Query: WP_Query()
With the single query I'm dealing with two loops - I call it loop within a loop. Structure is like below:
<?php
while( $my_query -> have_posts() ) :
$my_query -> the_post();
if( condition) { ?>
<div class="grid-box">
<div class="item">Item of this kind</div>
</div> <!-- .grid-box -->
<?php
}
if( condition) {
$someCounter = grab some counter here;
for( $inner = 0; $inner < $someCounter; $inner ++ ) {
?>
<div class="grid-box">
<div class="item">Item of that** kind#<?php echo $inner; ?></div>
</div> <!-- .grid-box -->
<?php
} //end for
}
endwhile;
?>
With CSS the query is doing excellent job for me, showing the items in nice grid-blocks. But with more items than a row, the items in second row colliding with the first. So I planned to put them within row class like:
<div class="row">
<!-- every 6 items within a grid -->
<div class="grid grid-first>Item of this kind</div>
<div class="grid>Item of this kind</div>
<div class="grid>Item of that** kind</div>
<div class="grid>Item of that** kind</div>
<div class="grid>Item of this kind</div>
<div class="grid grid-last>Item of that** kind</div>
</div>
<div class="row">
<div class="grid grid-first>Item of that** kind</div>
<div class="grid>Item of that** kind</div>
<div class="grid>Item of this kind</div>
</div>
Now I need to count the total items. How can I do this? Do I need to pass two counter and if so then how can I combine them both to count the exact counts and then use the count as conditions to load the div with .row? Please note as what I'm dealing with, the $inner counter is important for my dynamic code. But we can use the count for our total count.
For count you can use like this
<?php wp_count_posts( $type, $perm ); ?>
To get the published status type, you would call the wp_count_posts() function and then access the 'publish' property.
<?php
$count_posts = wp_count_posts();
$published_posts = $count_posts->publish;
?>
Counting pages status types are done in the same way as posts and make use of the first parameter. Finding the number of posts for the post status is done the same way as for posts.
<?php
$count_pages = wp_count_posts('page');
?>

Redirecting to a dynamic page

I have a page displaying blog posts [latest_posts.php] and another page that display single blog posts [blog.php] . I intend to link the image title in latest_posts.php so that it redirects to blog.php where it would display the particular post that was clicked.
latest_posts.php ---->
<div class="main blog">
<!-- Header -->
<h2 class="underline">
<span>What's new</span>
<span></span>
</h2>
<!-- /Header -->
<!-- Posts list -->
<ul class="post-list post-list-1">
<?php
/* Fetches Date/Time, Post Content and title */
include 'dbconnect.php';
$sql = "SELECT * FROM wp_posts";
$res = mysql_query($sql);
while ( $row = mysql_fetch_array($res) ) {
?>
<!-- Post #1 -->
<li class="clear-fix">
<!-- Date -->
<div class="post-list-date">
<div class="post-date-box">
<?php
//Timestamp broken down to show accordingly
$timestamp = $row['post_date'];
$datetime = new DateTime($timestamp);
$date = $datetime->format("d");
$month = $datetime->format("M");
?>
<h3> <?php echo $date; ?> </h3>
<span> <?php echo $month; ?> </span>
</div>
</div>
<!-- /Date -->
<!-- Image + comments count -->
<div class="post-list-image">
<!-- Image -->
<div class="image image-overlay-url image-fancybox-url">
<a href="post.php" class="preloader-image">
<?php
echo '<img src="', $row['image'], '" alt="' , $row['post_title'] , '\'s Blog Image" />';
?>
</a>
</div>
<!-- /Image -->
</div>
<!-- /Image + comments count -->
<!-- Content -->
<div class="post-list-content">
<div>
<!-- Header -->
<h4> <?php echo $row['post_title']; ?> </h4>
<!-- /Header -->
<!-- Excerpt -->
<p>
<?php echo $row ['post_content']; }?>
</p>
<!-- /Excerpt -->
</div>
</div>
<!-- /Content -->
</li>
<!-- /Post #1 -->
</ul>
<!-- /Posts list -->
Browse All Posts
</div>
<?php require_once('include/twitter_user_timeline.php'); ?>
blog.php --->
<?php require_once('include/header.php'); ?>
<body class="blog">
<?php require_once('include/navigation_bar_blog.php'); ?>
<div class="blog">
<div class="main">
<!-- Header -->
<h2 class="underline">
<span>What's new</span>
<span></span>
</h2>
<!-- /Header -->
<!-- Layout 66x33 -->
<div class="layout-p-66x33 clear-fix">
<!-- Left column -->
<!-- <div class="column-left"> -->
<!-- Posts list -->
<ul class="post-list post-list-2">
<?php
/* Fetches Date/Time, Post Content and title with Pagination */
include 'dbconnect.php';
//sets to default page
if(empty($_GET['pn'])){
$page=1;
} else {
$page = $_GET['pn'];
}
// Index of the page
$index = ($page-1)*3;
$sql = "SELECT * FROM `wp_posts` ORDER BY `post_date` DESC LIMIT " . $index . " ,3";
$res = mysql_query($sql);
//Loops through the values
while ( $row = mysql_fetch_array($res) ) {
?>
<!-- Post #1 -->
<li class="clear-fix">
<!-- Date -->
<div class="post-list-date">
<div class="post-date-box">
<?php
//Timestamp broken down to show accordingly
$timestamp = $row['post_date'];
$datetime = new DateTime($timestamp);
$date = $datetime->format("d");
$month = $datetime->format("M");
?>
<h3> <?php echo $date; ?> </h3>
<span> <?php echo $month; ?> </span>
</div>
</div>
<!-- /Date -->
<!-- Image + comments count -->
<div class="post-list-image">
<!-- Image -->
<div class="image image-overlay-url image-fancybox-url">
<a href="post.php" class="preloader-image">
<?php echo '<img src="', $row['image'], '" alt="' , $row['post_title'] , '\'s Blog Image" />'; ?>
</a>
</div>
<!-- /Image -->
</div>
<!-- /Image + comments count -->
<!-- Content -->
<div class="post-list-content">
<div>
<!-- Header -->
<h4> <?php echo $row['post_title']; ?> </h4>
<!-- /Header -->
<!-- Excerpt -->
<p> <?php echo $row ['post_content']; ?> </p>
<!-- /Excerpt -->
</div>
</div>
<!-- /Content -->
</li>
<!-- /Post #1 -->
<?php } // close while loop ?>
</ul>
<!-- /Posts list -->
<div><!-- Pagination -->
<ul class="blog-pagination clear-fix">
<?php
//Count the number of rows
$numberofrows = mysql_query("SELECT COUNT(ID) FROM `wp_posts`");
//Do ciel() to round the result according to number of posts
$postsperpage = 4;
$numOfPages = ceil($numberofrows / $postsperpage);
for($i=1; $i < $numOfPages; $i++) {
//echos links for each page
$paginationDisplay = '<li>' . $i . '</li>';
echo $paginationDisplay;
}
?>
<!--
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
-->
</ul>
</div><!-- /Pagination -->
<!-- /div> -->
<!-- Left column -->
</div>
<!-- /Layout 66x33 -->
</div>
</div>
<?php require_once('include/twitter_user_timeline.php'); ?>
<?php require_once('include/footer_blog.php'); ?>
Thanks in Advance.
Without seeing code for your problem I estimate the logic to be something like this..
On your latest_posts.php you would do something like this (assuming you have a variable like $post that contains the ID and title, or a schema like that):
<?php echo $post["title"]; ?>
Then on blog.php you'd need to grab the ID from the URL and look it up somehow..
<?php
$id = $_GET["id"];
$post = lookup_post_somehow($id);
if($post) {
// render post
} else {
// 404, blog post not found..
}
?>
You need to do some googling for tutorials. :) there is some great stuff around.
Your blogs are hopefully in a database. Those database records should each have a unique id.
On you latest_blogs page add ?id= (just an example) to pass the idover when the link is clicked.
Now, on your blog page the php variable $_GET['id'] will contain the blog id.
Hope that helps a bit.

Categories