Remove dates from array other than between FROM DATE and TO DATE - php

I have an array in php like this
Array (
[0] => Array (
[date] => 21/07/2014
[total_booking] => 1
)
[1] => Array (
[date] => 1/08/2014
[total_booking] => 1
)
[2] => Array (
[date] => 2/09/2014
[total_booking] => 2
)
)
if i get value $_POST['from_date'] and $_POST['to_date'] all array other than between this from_date,to_date should be removed.
Edit my code
foreach ($newarray as $newarray){
if ($newarray[Date] < $to_date && $from_date > $newarray[Date])
{
// i want to remove this row from array
}
}

Here's a solution using array_filter:
<?php
$data = array(
array(
'date' => '21/07/2014',
'total_booking' => '1'
),
array(
'date' => '1/08/2014',
'total_booking' => '1'
),
array(
'date' => '2/09/2014',
'total_booking' => '2'
)
);
$from_date = strtotime('01-08-2014'); //$_POST['from_date']
$to_date = strtotime('21-08-2014'); //$_POST['to_date']
$data = array_filter($data, function($array) use ($from_date, $to_date) {
$epoch = strtotime(str_replace('/', '-', $array['date']));
return $epoch >= $from_date && $epoch <= $to_date;
});
$data = array_values($data);
print_r($data);
Output:
Array
(
[0] => Array
(
[date] => 1/08/2014
[total_booking] => 1
)
)
Only one element is outputted because only 1/08/2014 is between 1/08/2014 and 21/08/2014.
For earlier PHP versions:
function filter($array) {
$from_date = strtotime('01-08-2014'); //$_POST['from_date']
$to_date = strtotime('21-08-2014'); //$_POST['to_date']
$epoch = strtotime(str_replace('/', '-', $array['date']));
return $epoch >= $from_date && $epoch <= $to_date;
}
$data = array_filter($data, 'filter');

Related

How to group the array by using array value, PHP

Here I am trying to fetch the income of a seller, but the problem is that I am unable to group the duplicate the array value into one.
Logic Function.
function getMonthlyIncomeOfSellerById($sellerId)
{
$data = array();
$ddd = array();
$query = "SELECT date_format(created_at,'%M'), product_id,sell_discount,SUM(sell_quantity) FROM sellers_sells WHERE seller_id=? AND YEAR(created_at) = YEAR(CURRENT_DATE()) GROUP BY date_format(created_at,'%M'),seller_id,product_id ORDER BY created_at";
$stmt = $this->con->prepare($query);
$stmt->bind_param('s',$sellerId);
$stmt->execute();
$stmt->bind_result($monthName,$productId,$sellDiscount,$sellQuantity);
while ($stmt->fetch())
{
$d['monthName'] = $monthName;
$d['productId'] = $productId;
$d['sellDiscount'] = $sellDiscount;
$d['sellQuantity'] = $sellQuantity;
array_push($data, $d);
}
$stmt->close();
$netProfit = 0;
$maxProfit = 0;
foreach ($data as $dt)
{
$product = $this->getProductById($dt['productId']);
$product['productPrice'] = ($product['productPrice']/100)*$dt['sellDiscount'];
if ($product['productName']==='PRODUCT NAME' && $product['productBrand']==='PRODUCT BRAND' && $product['productSize']==='50ML')
{
$maxPrice = $product['productPrice']*$dt['sellQuantity'];
$price = ($product['productPrice']-10)*$dt['sellQuantity'];
}
else if ($product['productName']==='PRODUCT NAME' && $product['productBrand']==='PRODUCT BRAND' && $product['productSize']==='100ML')
{
$maxPrice = $product['productPrice']*$dt['sellQuantity'];
$price = ($product['productPrice']-15)*$dt['sellQuantity'];
}
else if ($product['productName']==='PRODUCT NAME' && $product['productBrand']==='PRODUCT BRAND' && $product['productSize']==='200ML')
{
$maxPrice = $product['productPrice']*$dt['sellQuantity'];
$price = ($product['productPrice']-30)*$dt['sellQuantity'];
}
$netProfit = $netProfit+$price;
$maxProfit = $maxProfit+$maxPrice;
$dts['monthName'] = $dt['monthName'];
$dts['netProfit'] = $netProfit;
$dts['maxProfit'] = $maxProfit;
array_push($ddd, $dts);
}
print_r($ddd);
}
Getting the out put with duplicate value.
Array
(
[0] => Array
(
[monthName] => January
[netProfit] => 2050
[maxProfit] => 2800
)
[1] => Array
(
[monthName] => March
[netProfit] => 2214
[maxProfit] => 3024
)
[2] => Array
(
[monthName] => March
[netProfit] => 4149
[maxProfit] => 5604
)
[3] => Array
(
[monthName] => March
[netProfit] => 4523
[maxProfit] => 6148
)
)
But here I want to group it with the month, and add all the values into one.
Like this.
Array
(
[0] => Array
(
[monthName] => January
[netProfit] => 2050
[maxProfit] => 2800
)
[1] => Array
(
[monthName] => March
[netProfit] => 10886
[maxProfit] => 14776
)
)
How can I do this?
Thanks
You could group by 'month' by usign the monthName as key. If the key doesn't exists, create a new entry with default values. Then, you could add (+) the current value from the data.
$monthName = $dt['monthName'];
if (!isset($ddd[$monthName])) {
$ddd[$monthName] = [
'monthName' => $monthName,
'netProfit' => 0,
'maxProfit' => 0,
];
}
$ddd[$monthName]['netProfit'] += $netProfit;
$ddd[$monthName]['maxProfit'] += $maxProfit;
Instead of
$dts['monthName'] = $dt['monthName'];
$dts['netProfit'] = $netProfit;
$dts['maxProfit'] = $maxProfit;
array_push($ddd, $dts);
To remove added keys, you could use :
$ddd = array_values($ddd);

PHP array_push with custom key

I'm trying to merge two arrays which have a custom key using array_push, but when I use array_push it removes the custom key.
For example if I just create a normal array with a custom key it works fine:
$price_arr = array();
$date = '2017-08-01';
$insert_data = array(
$date => array(
'adult_1' => '10'
)
);
print_r($insert_data);
The result is:
Array ( [2017-08-01] => Array ( [adult_1] => 10 ) )
However if I use array push it removes the custom key, for example:
$price_arr = array();
$date = '2017-08-01';
$insert_data = array(
$date => array(
'adult_1' => '10'
)
);
array_push($price_arr, $insert_data);
$insert_data = array(
$date => array(
'child_1' => '2'
)
);
array_push($price_arr, $insert_data);
print_r($price_arr);
The result is:
Array ( [0] => Array ( [2017-08-01] => Array ( [adult_1] => 10 ) ) [1] => Array ( [2017-08-01] => Array ( [child_1] => 2 ) ) )
The result I'm trying to produce is:
Array ( [2017-08-01] => Array ( [adult_1] => 1 [child_1] => 2 ) )
Any help appreciated!
why not just do
$arr['custom_key'] = 'your value';
you do are not bound to use array_push , just assign it and it is done.
$price_arr = array();
$date = '2017-08-01';
$price_arr[$date]['adult_1'] = 10;
$price_arr[$date]['child_1'] = 2;
print_r($price_arr);
You have to use array_merge instead of array_push
$price_arr = array();
$date = '2017-08-01';
$insert_data = array(
$date => array(
'adult_1' => '10'
)
);
$price_arr = array_merge($insert_data);
$insert_data = array(
$date => array(
'child_1' => '2'
)
);
$price_arr[$date] = array_merge($price_arr[$date],$insert_data[$date]);
echo "<pre>";
print_r($price_arr);

filter an array by its element

Below is the array inside loop:
I want to filter this array by [date-begin] and [date-end]
For eg if I post startdate = 2015-06-29 and enddate = 2015-08-29
then array data between this range should come.
I tried:
1. array_slice
2.foreach(range ($startdate,$enddate) as $data){
echo "Age: {$data}<br />";
}
Array
(
[name] => MCLE 201
[date-begin] => 2015-06-29
[date-end] => 2015-06-29
)
Array
(
[name] => MCLE 201
[date-begin] => 2015-07-29
[date-end] => 2015-07-29
)
Array
(
[name] => MCLE 201
[date-begin] => 2015-08-29
[date-end] => 2015-08-29
)
Array
(
[name] => MCLE 201
[date-begin] => 2015-09-29
[date-end] => 2015-09-29
)
#Aashi you can do it with foreach() like below:
<?php
$yourArray = array(
array(
"name" => "MCLE 201",
"date-begin" => "2015-06-29",
"date-end" => "2015-06-29"
),
array(
"name" => "MCLE 201",
"date-begin" => "2015-07-29",
"date-end" => "2015-07-29"
),
array(
"name" => "MCLE 201",
"date-begin" => "2015-08-29",
"date-end" => "2015-08-29"
),
array(
"name" => "MCLE 201",
"date-begin" => "2015-09-29",
"date-end" => "2015-09-29"
)
);
$startdate = "2015-06-29";
$enddate = "2015-08-29";
$filteredArr = array();
foreach($yourArray as $value) {
if($startdate <= $value["date-begin"] && $enddate >= $value["date-end"]){
$filteredArr[] = $value;
}
}
echo "<pre>";
print_r($filteredArr);
Try this:
$filterArray = array();
foreach($arr as $key=>$val){
if(strtotime($val['date-begin']) >= strtotime($postedDateBegin) && strtotime($val['date-end']) <= strtotime($postedDateEnd)){
$filterArray[] = $val;
}
}
Click here to check output
this is proper solution for you question !
function date_is_between($start_date, $end_date, $date){
$start_date = date('Y-m-d',strtotime($start_date));
$end_date = date('Y-m-d',strtotime($end_date));
$date = date('Y-m-d',strtotime($date));
$match = FALSE;
if (($date => $start_date) && ($date <= $end_date))
$match = TRUE;
return $match;
}
function date_between($element, $start_date, $end_date)
{
$match = FALSE
if(date_is_between($element['date-begin'], $element['date-end'], $element['date-begin']) && date_is_between($element['date-begin'], $element['date-end'], $element['date-end']))
$match = TRUE;
return $match;
}
$filter_array = array_filter($data, "date_between");

assign variable for nested array and spliting it

I am getting nested array reply. It is contain date, time and day I want to break that. How can i do that.
This is my reply
Array
(
[code] => 202
[message] => Accepted
[data] => Array
(
[result] => Array
(
[15:45~31-10-2016 Mon] => Array
(
[Sday] =>
[Ttime] => 15:45
[Smonth] =>
"[15:45~31-10-2016 Mon] => Array" how to assign variable and how can i break this into day ,date and time variable
As mentioned in Mohammad's comment on your question,
You should use preg_split function.
$str = key($array['data']['result']); // 15:45~31-10-2016 Mon
$res = preg_split("/[~\s]/", $str);
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => 15:45
[1] => 31-10-2016
[2] => Mon
)
If you have only single element in result array, use extract and explode to retrieve the values from man array: Something like -
$result = $array['data']['result'];
$date = key($result);
$day = extract($result[$date]);
var_dump($date); // 15:45~31-10-2016 Mon
var_dump($Ttime); // will output 15:45
$date = explode(' ', $date);
$dateString = substr($date[0], strpos($date[0], "{$Ttime}~") + 1); //31-10-2016
$week = $date[1]; // var_dump($week); will give `Mon`
Given:
$result = array(
'code' => '202',
'message' => 'Accepted',
'data' => array(
'result' => array(
'15:45~31-10-2016 Mon' => array(
'Sday' => '',
'Ttime' => '15:45',
'Smonth' => ''
)
)
)
);
you can do this:
$data = $result['data']['result'];
$dateKey = key($data);
$dateString = preg_split("/[~\s]/", $dateKey);
$date = array(
'day' => $dateString[2],
'date' => $dateString[1],
'time' => $dateString[0]
);
var_dump($date);
or this:
$data = $result['data']['result'];
$dateKey = key($data);
$dateString = preg_replace("/[~\s]/", ' ', $dateKey);
$dateObj = DateTime::createFromFormat('H:i d-m-Y D', $dateString);
$date = array(
'day' => $dateObj->format('D'),
'date' => $dateObj->format('m-d-Y'),
'time' => $dateObj->format('H:i')
);
var_dump($date);

Manipulating arrays of dates in PHP

I'm having a lot of difficulty approaching a piece of code in PHP. I have an array of dates and values, for example
dates = (2014-12-01,2014-12-02,2014-12-08,2014-12-09,2014-12-10,2014-12-11)
values = (5,3,7,8,9,2)
You'll note that 12/01 is a Monday, as is 12/08. I'd like to form 4 arrays from these two arrays:
monday = (5,7)
tuesday = (3,8)
wednesday = (0,9)
thursday = (0,2)
You'll note that the arrays are formed by grabbing the values associated with the days of the week. However, in the case that a Wednesday date exists, for example, but the prior Tuesday does not, then the array should have a "0". In other words, the 4 arrays should all be the same length.
Can anyone help me write code in PHP to achieve this? Thanks in advance!
NOTE: So far, I have only determined how to find the day of the week from a date: date('l', strtotime("2014-12-08")); I really can't figure out the general algorithm to solve this.
$dates = array( '2014-12-01','2014-12-02','2014-12-08','2014-12-09',
'2014-12-10','2014-12-11' );
$values = array( 5, 3, 7, 8, 9, 2 );
$date = strtotime(min($dates));
$stop = strtotime(max($dates));
$dates = array_flip($dates);
$out = array();
while($date <= $stop)
{
$tmp = date('Y-m-d', $date);
$out[date('l', $date)][] = isset($dates[$tmp]) && isset($values[$dates[$tmp]]) ?
$values[$dates[$tmp]] : 0;
$date = strtotime('+1 day', $date);
}
print_r($out);
Result:
Array
(
[Monday] => Array
(
[0] => 5
[1] => 7
)
[Tuesday] => Array
(
[0] => 3
[1] => 8
)
[Wednesday] => Array
(
[0] => 0
[1] => 9
)
[Thursday] => Array
(
[0] => 0
[1] => 2
)
[Friday] => Array
(
[0] => 0
)
[Saturday] => Array
(
[0] => 0
)
[Sunday] => Array
(
[0] => 0
)
)
ps: how can I get the an array of all the dates included in the "dates" array associated with only all the Mondays?
Modify the code as, for example:
$tmp = date('Y-m-d', $date);
$exists = isset($dates[$tmp]) && isset($values[$dates[$tmp]]);
$out[date('l', $date)]['numbers'][] = $exists ? $values[$dates[$tmp]] : 0;
if ($exists) $out[date('l', $date)]['dates'][] = $tmp;
$date = strtotime('+1 day', $date);
You'll get an output as (example for monday)
[Monday] => Array
(
[numbers] => Array
(
[0] => 5
[1] => 7
)
[dates] => Array
(
[0] => 2014-12-01
[1] => 2014-12-08
)
)
Might be a better way to get the 0s in there without another loop but I'm headed out:
foreach($dates as $key => $val) {
$day = date('l', strtotime($val));
$result[$day][] = $values[$key];
}
foreach($result as &$val) {
if(count($val) == 1) {
array_unshift($val, 0);
}
}
print_r($result);

Categories