sum of 2D array in php - php

I have a situation where I need to generate total sales of each month.
I can show total sales of 12 month in a certain area but I need to show total sales of any month of a certain area. i.e: total sales of June at Head Office area.
my sample code is as follows:
while($area = mysql_fetch_array($exe_area))
{
for ($m=1; $m<=12; $m++) {
.........
echo $total_sold;
$sales_of_year+= $total_sold;
} // end of month listing....
echo $sales_of_year;
} // end of area listing...

U may try this !!!
$tmp = explode( '|', $str );
$data = array();
foreach ( $tmp as $k => $v )
{
$data[] = explode( ',', $v );
}

It looks like your data is being retrieved from the database, in which case you can extract the total sum with your query:
SELECT SUM(column_name) FROM table_name;
Or, to analyse a particular month, depending on your database schema, you can do:
SELECT SUM(column_name) FROM table_name WHERE month = 'June';

Related

Symfony calculate number of days based on date

I am trying to calculate price for number of days from 1-21 based on date.
HomeController
$Sql = ' SELECT DISTINCT
a.property_id, a.date, a.minimum_stay,
a.maximum_stay,a.quantity,
a.arrival_allowed,a.departure_allowed,
p.duration, p.persons, p.amount,
p.extra_person_price, p.minimum_stay AS price_minimum_stay,
p.maximum_stay AS price_maximum_stay, p.weekdays,
p.period_till, p.period_from,
datediff(p.period_till, p.period_from) AS number_of_days
FROM availabilities AS a
JOIN prices AS p
ON a.property_id=p.property_id
WHERE a.minimum_stay >0
AND a.maximum_stay < 22
AND a.date >= p.period_from
AND a.date <= p.period_till
';
$Stm = $this->getEntityManager()->getConnection()->prepare($Sql);
$Stm->execute();
return $Stm->fetchAll(PDOConnection::FETCH_ASSOC);
public function CalculatePrice($persons, $extra_person_price, $date, $amount, $duration, $period_till, $period_from)
{
//loop through persons
foreach ($persons as $person) {
//calculate price for persons
if ($person > 1) {
$amount += $person * $extra_person_price;
}
//array to link parameters with database fields
$tmp = array(
"date" => $date,
"person" => $person,
"price_person" => number_format($amount / 100, 2, '.', ',')
);
//loop through $tmp an add value from 2 to 21 to day an add this to $tmp array with calculated value
//$x=$number_of_days;
//$days = (strtotime($period_till) - strtotime($period_from)) / (60 * 60 * 24);
for ($x = 1; $x <= 21; ++$x) {
if ($x >1) {
$tmp["day$x"] = $tmp["day".($x-1)] + number_format($amount / 100, 2, '.', ',');
//number_format(($amount * $x) / 100, 2, '.', ',');
} else {
$tmp["day$x"] = "0.00";
}
$price_per_person[] = $tmp;
}
return $price_per_person;
}
I am also calculating price for number of persons but that part is good. Right now I have made a for loop and stored numbers from 1 to 21 for number of days see my second for loop in function CalculatePrice. But this part not good I need to calculate this based on date. for example:
Regularly price for most of days is 123 Euro. let say on 3 September a day cost 250 euro and on 7 September it cost 300 Euro. So let say A person want to stay for 5 days and he arrives at 3 September so the calculation will be: 250 + 123 + 123 + 123 + 300 = 919 Euro.
But I need this to be based on date. I have tried with period_from and period_til but so far no luck. Can someone give an example or some useful hints how I can do this in a for loop like my second for loop.
I have solved this question based on the theory T. Abdelmalek gave me. I made an array and stored date and price of each date in and loped through. The answer has been deleted somehow I don't know how to mark as solved
You can use date_diff like that:
First date = $leave->getLeaveFrom();
Second date = $leave->getLeaveTo();
$diff = date_diff($leave->getLeaveFrom(),$leave->getLeaveTo());
Results = var_dump($diff);

PHP & MySQL - How to remove first value if it is (,)

I have a flowing in my little project to display amount and the date from two different columns. One thing to note is that it stores multiple values in those columns which are separated by (,):
$apaidArray = explode(',', $apaid);
$daterArray = explode(',', $dater);
for ( $i = 0; $i < count($apaidArray); $i++ ){
echo $apaidArray[$i].' repaid on ' .$daterArray[$i].'<br>';
}
As the result of the (,) which is placed initially before the repayment amount is entered this would display the following if there are only two entries into db:
apaid = , 80, 20
dater = , 12.07.2017, 13.07.2017
Result looks like:
repaid on
80 repaid on 12.07.2017
20 repaid on 13.07.2017
So my question is is there a way of removing the (,) before displaying result only if it is the first value in that column so that the resulting would be:
80 repaid on 12.07.2017
20 repaid on 13.07.2017
Any help is greatly appreciated.
Run trim on both values, with the character mask set to ','.
for ( $i = 0; $i < count($apaidArray); $i++ ) {
if (!empty($apaidArray[$i])) {
echo $apaidArray[$i].' repaid on ' .$daterArray[$i].'<br>';
}
}
<?php
$apaid = ', 80, 20';
$apaid = ltrim($apaid,','); //$apaid = ltrim($apaid,', ');
?>

PHP Array Merge Issue

I have a table of races that have the race name, race id, and race date.
I am trying to build a single array (it has to be a single array returned via a function call) which would contain a list of the races in the following format:
,,---2017---
The Resolution AR, 58, 1.14.2017
Heartbreaker AR, 59, 2.11.2017
,,---2016---
The Blue Ridge AR, 38, 5.21.2016
The Fathers Day AR, 43, 6.18.2016
Adventure Bike (Santos), 54, 7.30.2016
,,---2015---
Gemini Springs AR, 4, 12.14.2015
I am almost there! But I am having one issue.
This is the current code I have:
function get_races() {
// get all the years that have races
$years = $wpdb->get_results("
select DATE_FORMAT(r.race_date,'%Y') year
from race_calendar r
group by DATE_FORMAT(r.race_date,'%Y')
order by DATE_FORMAT(r.race_date,'%Y') desc;
");
// loop through all years that have races
foreach ( $years as $year ) {
// add year header to array
$year_header = array(array ('','','---'.$year->year.'---'));
// get races for this particular year
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
where DATE_FORMAT(r.race_date,'%Y') = ".$year->year."
order by r.race_date;
", ARRAY_N);
// merge the year header and the races into an array
$merged_arr = array_merge($year_header, $races);
}
return $merged_arr;
}
// call function to get list of races
$races = get_races();
// display the list of races (with the year separator)
foreach ( $races as $race )
{
echo $race['0'] . ',' . $race['1'] . ',' . $race['2'] . '<br />';
}
It works. But problem is, that code above only displays the last iteration of the years loop, in this case, 2015:
,,---2015---
Gemini Springs AR, 4, 12.14.2015
Obviously $merged_arr is begin reset with each iteration of the years loop
How can I update it so that the resulting array in the function contains the data for all the iterations of the years loop?
You can do this all with a single query. Just select all the rows, then loop over the results and detect when the year changes from the previous iteration to know when to output your separator row.
$last = null;
$query = <select * from race_calendar order by race_date>
foreach ($query as $row) {
$year = // year of $row['race_date']
if ($year != $last) {
// new year, output separator line
$last = $year;
}
// output data line
}

Replacing redundant dates in DB query with symbol (MySQL/PHP)

I have a database query that displays a list of historic events in chronological order, like this:
(URL = MySite/Calendar/January_1)<br>
On this day in history...<br>
1968 - A volcano erupted.<br>
1968 - A country was invaded.<br>
1968 - Someone had a hit song.<br>
1970 - A famous person was born.
I'd like to know if there's a way to display a year just once, so the display looks like this:
1968 - A volcano erupted.<br>
• A country was invaded.<br>
• Someone had a hit song.<br>
1970 - A famous person was born.
Let's start with a database table (calendar_px) that lists the dates of various historic political events. The table has five fields -
1) N (a simple numerical key)
2) URL (values - such as May_1 - match page URL's)
3) Year (e.g. 1970, but the field type is INT, not Year, which only goes back to 1901)
4) Brief (some brief content)
5) Date (field type will be either date or datetime; I'm not actually using this field at the moment)
Here's what my code looks like (where $MyURL equals the page URL; e.g. January_1):
$stm = $pdo->prepare("SELECT Cal2.N, Cal2.URL, Cal2.Date, Cal2.Year, Cal2.Brief
FROM calendar_px Cal2
WHERE Cal2.URL = :MyURL
ORDER BY Cal2.Year");
$stm->execute(array(
'MyURL'=>$MyURL
));
while ($row = $stm->fetch())
{
$Year = $row['Year'];
$Brief[] = ''.$Year.' – '.$row['Brief'].'';
}
Then, I display a list of historic events like this...
echo join( $Brief, '<br>' );
I don't think it really changes anything, but I should mention that I have a similar set up on several websites; everything is the same except for the table names:
calendar_gw, calendar_gz, calendar_gs, calendar_px, calendar_sl
Accordingly, I've joined all five tables together with a UNION command. Here's a portion of the query:
$stm = $pdo->prepare("SELECT CGW.N, CGW.URL, CGW.Date, CGW.Year, CGW.Brief
FROM calendar_gw CGW
WHERE CGW.URL = :MyURL
UNION ALL
SELECT CGZ.N, CGZ.URL, CGZ.Date, CGZ.Year, CGZ.Brief
FROM calendar_gz CGZ
WHERE CGZ.URL = :MyURL
UNION ALL
SELECT CSL.N, CSL.URL, CSL.Date, CSL.Year, CSL.Brief
FROM calendar_sl CSL
WHERE CSL.URL = :MyURL
ORDER BY Year");
$stm->execute(array(
'MyURL'=>$MyURL
));
Anyway, my goal is the same; to replace redundant dates (years) with some sort of "dingbat" or symbol.
$prevYear = null;
while ($row = $stm->fetch())
{
$Year = $row['Year'];
if ($Year == $prevYear) {
$YearStr = '• ';
} else {
$YearStr = $Year . ' $#8211; ';
$prevYear = $Year;
}
$Brief[] = $YearStr.$row['Brief'];
}
P.S. You don't need to concatenate '' at each end of the string.
Looks like you need to group resultset before outputting:
$events = array();
while($row = $stm->fetch()){
$year = $row['Year']; // current year
if(!isset($events[$year]){ // if no such group
$events[$year] = array(); // create group
}
$events[$year][] = $row['Brief']; // add data to year group
}
// Output:
foreach($events as $year => $event){
echo $year, ':<br>'; // show year;
foreach($event as $data){
echo $data, '<br>'; // show row;
}
}
Also, you may change output to your model, easily:
foreach($events as $year => $event){
echo $year, ' • ', implode('<br>• ', $event);
}

How to break up reports by month with php and mysql?

I'm trying to do something relatively simple here. Basically I have a table with a bunch of rows in it marked with a timestamp (format: 2009-05-30 00:14:57).
What I'm wanting to is do is a query which pulls out all of the rows, and splits them by the month so I'm left with a final result like:
February
rowID name order date
rowID name order date
rowID name order date
January
rowID name order date
rowID name order date
rowID name order date
etc.
I have a few vague ideas how to do this - they just seem long winded.
One of the ways would be to do a query for each month. I'd derive what the current month is in PHP then construct a for() which goes back a certain number of months.
like:
$currentmonth = 8;
$last6months = $currentmonth - 6;
for($i = $currentmonth; $i == $last6months; $i--) {
$sql = 'SELECT * FROM reports WHERE MONTH(reports.when) = $currentmonth ';
$res = mysql_query($sql);
// something would go here to convert the month numeral into a month name $currentmonthname
echo $currentmonthname;
while($row = mysql_fetch_array($res)) {
// print out the rows for this month here
}
}
Is there a better way to do this?
It's better to fetch all data once,ordered by month..
Then while fetching with php you can store your current month in a variable (for example $curMonth) and if there is a change in the month, you echo "New Month"...
Executing a query is slow, it's better to minimize your "conversations" with the db..
Don't forget that you have to deal with years aswell. If you have two records, one for January '09 and one for January '08, your results may be skewed.
Best to follow Svetlozar's advice and fetch all data at once. Once you have it in memory, use PHP to segment it into something usefull:
$monthData = array();
$queryResult = mysql_query("
SELECT
*,
DATE_FORMAT('%m-%Y', when) AS monthID
FROM
reports
WHERE
YEAR(when) = 2009 AND
MONTH(when) BETWEEN 5 and 11
");
while ($row = mysql_fetch_assoc($queryResult))
{
if (!isset($monthData[$row['monthID']]))
$monthData[$row['monthID']] = array();
$monthData[$row['monthID']][] = $row;
}
mysql_free_result($queryResult);
foreach($monthData as $monthID => $rows)
{
echo '<h2>Data for ', $monthID, '</h2>';
echo '<ul>';
foreach($rows as $row)
{
echo '<li>', $row['someColumn'], '</li>';
}
echo '</ul>';
}
You could change your SQL query to get your entire report. This is much more efficient than querying the database in a loop.
select
monthname(reports.when) as currentmonth,
other,
fields,
go,
here
from reports
order by
reports.when asc
You could then use this loop to created a nested report:
var $currentMonth = '';
while($row = mysql_fetch_array($res)) {
if($currentMonth !== $row['currentMonth']) {
$currentMonth = $row['currentMonth']);
echo('Month: ' . $currentMonth);
}
//Display report detail for month here
}
*Note: Untested, but you get the general gist of it I'm sure.
This is the SQL script:
SELECT*, DATE_FORMAT(fieldname,'%Y-%m') AS report FROM bukukecil_soval WHERE MONTH(fieldname) = 11 AND YEAR(fieldname)=2011
I hope you know where you should put this code :D

Categories