Check if multiple datetime are same in php foreach - php

I want to split items which have same date and different date.
foreach ($cart->getAllItems() as $item)
{
$pickupDateTime = $item->getCartPickupDate().' '.$itemgetCartPickupTime();
$pickupDateTime = date('Y-m-d G:i:s', strtotime($pickupDateTime)) //2018-03-09 6:03:00 or 2018-03-09 21:10:00
// Split items here with same Date //
if(Dates are Same Condition){
$items_normal[]= $item->getProductId();
}else
{
//If Dates Are diffrent
$ites_special[]= $item->getProductId();
}
}
Need to compare if dates are same in first if condition and in else part the items which have different dates.
Look at the following arrays, in this I have same date and time, I need to club those which have same date and time. In below example, the 3rd one must be come under first Array as it has different time i.e. 6:05 instead of 6:03
Array
(
[1] => Array
(
[product_id] => 742
[qty] => 1
[date] => 03/09/2018
[time] => 06:03 AM
[tax] => 0
[splinst] => null
)
[2] => Array
(
[product_id] => 743
[qty] => 1
[date] => 03/09/2018
[time] => 06:03 AM
[tax] => 0
[splinst] => null
)
)
Array
(
[3] => Array
(
[product_id] => 744
[qty] => 1
[date] => 03/09/2018
[time] => 06:03 AM
[tax] => 0.12
[splinst] => null
)
[4] => Array
(
[product_id] => 757
[qty] => 1
[date] => 03/09/2018
[time] => 06:05 AM
[tax] => 0.25
[splinst] => null
)
)

You should use the DateTime object:
$pickupDateTime = $item->getCartPickupDate().' '.$itemgetCartPickupTime();
$pickupDateTime = new DateTime($pickupDateTime);
You can compare two DateTime objects which each other:
if ($dateTimeObject1 == $dateTimeObject2) {
// both have same date and time
}
Be aware that you should not use strict comparison (===) here as it would check if it is the same object and not if the DateTime is the same.
If you need to compare only the date and ignore the time you can call setTime on both objects to reset the time to 0:
$dateTimeObject1->setTime(0, 0, 0);
$dateTimeObject2->setTime(0, 0, 0);
if ($dateTimeObject1 == $dateTimeObject2) {
// both have the same date
}

You could store the date in keys into an array to group items :
foreach ($cart->getAllItems() as $item)
{
$pickupDateTime = $item->getCartPickupDate().' '.$itemgetCartPickupTime();
$pickupDateTime = date('Y-m-d G:i:s', strtotime($pickupDateTime)) //2018-03-09 6:03:00 or 2018-03-09 21:10:00
$items_special[$pickupDateTime][] = $item->getProductId();
}
foreach ($items_special as $date => $items) {
if (count($items) > 1) {
$items_normal = $items ;
unset($items_special[$date]);
break;
}
}
$items_special = array_values($items_special);
So, $items_special will look like :
Array
(
[0] => Array
(
[product_id] => 757
[qty] => 1
[date] => 03/09/2018
[time] => 06:05 AM
[tax] => 0.25
[splinst] => null
)
)
And $items_normal will look like :
Array
(
[0] => Array
(
[product_id] => 742
[qty] => 1
[date] => 03/09/2018
[time] => 06:03 AM
[tax] => 0
[splinst] => null
)
[1] => Array
(
[product_id] => 743
[qty] => 1
[date] => 03/09/2018
[time] => 06:03 AM
[tax] => 0
[splinst] => null
)
[2] => Array
(
[product_id] => 744
[qty] => 1
[date] => 03/09/2018
[time] => 06:03 AM
[tax] => 0.12
[splinst] => null
)
)

Related

Loop through an array and group prices by month, Morris chart

I want to group results by month, to be precise Sum of total prices for each month, but i don't understand how i can divide months, then Sum price for each month.
This is required for morris chart like this
$data2[] = array(
'y' => $month,
'a' => price,
'b' => ''
);
I was using before query to get this results and was a easy way to do it, but now with code is different story.
Any help with explanation of how each segment of code is work will be so nice, so i can avoid problems like this one in future.
I need something like this :
$month = [May, June];
$price = [Sum of all prices for May, Sum of all prices for June];
This is a code :
$monthsArray = array();
// get all dates in array
foreach ($array as $key) {
// convert dates to short format, month-year -> Jun-18
$monthsArray[] = date('M-y', strtotime($key['time']));
}
$months = array();
foreach ($monthsArray as $date) {
$mon = substr($date, 0, 6);
if (!in_array($mon, $months)) array_push($months, $mon);
}
foreach ($months as $m) {
// final array for chart
$data2[] = array('y'=>$m, 'a'=>'', 'b'=>'');
}
$morris = json_encode($data2);
This is array i have
Array
(
[0] => Array
(
[price] => -1835.25
[time] => 2018-05-29 16:53:38
)
[1] => Array
(
[price] => -1743.52
[time] => 2018-05-29 16:53:39
)
[2] => Array
(
[price] => -4445.55
[time] => 2018-05-31 13:21:04
)
[3] => Array
(
[price] => -34647.04
[time] => 2018-05-31 18:29:43
)
[4] => Array
(
[price] => 16888.41
[time] => 2018-06-01 15:05:24
)
[5] => Array
(
[price] => 14369.05
[time] => 2018-06-07 14:44:21
)
[6] => Array
(
[price] => -49579.69
[time] => 2018-06-11 09:14:42
)
[7] => Array
(
[price] => -33300.94
[time] => 2018-06-08 23:50:29
)
[8] => Array
(
[price] => 4413.21
[time] => 2018-06-12 07:15:52
)
[9] => Array
(
[price] => 2724.69
[time] => 2018-06-12 07:15:46
)
[10] => Array
(
[price] => 10224.03
[time] => 2018-06-08 14:00:13
)
[11] => Array
(
[price] => -797.92
[time] => 2018-06-08 13:54:08
)
[12] => Array
(
[price] => -25157.34
[time] => 2018-06-11 11:31:31
)
[13] => Array
(
[price] => 2701.6
[time] => 2018-06-11 14:32:08
)
[14] => Array
(
[price] => 2038.92
[time] => 2018-06-12 07:15:48
)
[15] => Array
(
[price] => -10541.58
[time] => 2018-06-15 10:35:58
)
)
EDIT:
I manage to group months as you can see in updated code and now i am getting only 2 results as i should be, now its just a issue with SUM of data for each month.
This is what i am getting in console
0: {y: "May-18", a: "", b: ""}
1: {y: "Jun-18", a: "", b: ""}

How to split array data returned from json string in php

I have json return string like given below. I want to extract cancellation Policy list of objects like cutoff Time and refund In Percentage. I tried using for-loop but it didn't help me. Can you please help me on extracting this.
Array (
[apiStatus] => Array ( [success] => 1 [message] => SUCCESS ) <br>
[apiAvailableBuses] => Array ( <br>
[0] => Array ( [droppingPoints] => [availableSeats] => 41 <br>[partialCancellationAllowed] => [arrivalTime] => 08:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:00PM [location] => Ameerpet,|Jeans Corner 9687452130 [id] => 6 ) [1] => Array ( [time] => 09:15PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 09:10PM [location] => Kondapur,Toyota Show room [id] => 2244 ) ) [operatorName] => Deepak Travels [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6622 [fare] => 800 [busType] => 2+1 Hi-Tech Non A/c [routeScheduleId] => 6622 [commPCT] => 0 [operatorId] => 213 [inventoryType] => 0 ) <br>
[1] => Array ( [droppingPoints] => [availableSeats] => 41 [partialCancellationAllowed] => [arrivalTime] => 07:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:10PM [location] => Ameerpet,|Jeans Corner [id] => 6 ) [1] => Array ( [time] => 09:00PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 08:30PM [location] => KUKATPALLY,JNTU [id] => 2230 ) ) [operatorName] => Dhanunjayabus [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6743 [fare] => 900 [busType] => VOLVO [routeScheduleId] => 6743 [commPCT] => 0 [operatorId] => 233 [inventoryType] => 0 )
)
)
Use a foreach() for it like so:
foreach ($your_response['apiAvailableBuses'] as $el) {
$cancellationPolicy[] = $el['cancellationPolicy'];
}
Try this:
foreach($data['apiStatus']['apiAvailableBuses'] as $item) {
foreach($item['cancellationPolicy'] as $key => $json) {
$jsonDecoded = json_decode($json, true);
// And you will have access to the data like this
// $jsonDecoded['cutoffTime'];
// $jsonDecoded['refundInPercentage'];
}
}
$response = json_decode($apiResponse);
$cancellationPolicies = [];
foreach ($response->apiAvailableBuses as $availableBus) {
$cancellationPolicies[] = $availableBus['cancellationPolicy'];
// if you want to display something you can simply do it like this;
echo $availableBus['cancellationPolicy']->cutoffTime;
}

php print array contents

I need help printing the contents of this function:
which came from:
http://drupalcontrib.org/api/drupal/contributions%21flag%21flag.module/function/flag_get_user_flags/7
$userFlags = flag_get_user_flags('user', null, $node->uid, null, false);
If I use print_r:
print '<pre>';
print_r(flag_get_user_flags('user', null, $node->uid, null, false));
print '</pre>';
I get -
Array
(
[follow] => Array
(
[13] => stdClass Object
(
[flagging_id] => 20
[fid] => 5
[entity_type] => user
[entity_id] => 13
[uid] => 1
[sid] => 0
[timestamp] => 1385845849
)
[15] => stdClass Object
(
[flagging_id] => 21
[fid] => 5
[entity_type] => user
[entity_id] => 15
[uid] => 1
[sid] => 0
[timestamp] => 1385912237
)
[17] => stdClass Object
(
[flagging_id] => 22
[fid] => 5
[entity_type] => user
[entity_id] => 17
[uid] => 1
[sid] => 0
[timestamp] => 1386040495
)
[18] => stdClass Object
(
[flagging_id] => 23
[fid] => 5
[entity_type] => user
[entity_id] => 18
[uid] => 1
[sid] => 0
[timestamp] => 1386040515
)
[21] => stdClass Object
(
[flagging_id] => 24
[fid] => 5
[entity_type] => user
[entity_id] => 21
[uid] => 1
[sid] => 0
[timestamp] => 1386043939
)
[14] => stdClass Object
(
[flagging_id] => 25
[fid] => 5
[entity_type] => user
[entity_id] => 14
[uid] => 1
[sid] => 0
[timestamp] => 1386129658
)
)
)
When I use:
foreach($userFlags as $item) {
echo $item;
}
All i get is the word "Array" printed. If your familiar with drupal ideally I need to convert each entity_id to its author. printing the 13,15 etc. is a good start for me.
thanks for any help-
You have an array in an array. Pull the inner array out before your foreach:
$follow = $userFlags['follow'];
foreach($follow as $item) {
echo $item->entity_id;
}
Or more succinctly:
foreach($userFlags['follow'] as $item) {
echo $item->entity_id;
}
//#parram $data-array,$d-if true then die by default it is false
//#author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT. There are 2 Patameters 1.$data - It can be Array or String 2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can write like this..
$userFlags = flag_get_user_flags('user', null, $node->uid, null, false);
foreach($userFlags as $item) {
p($item['id']); // If it is array
p($item->id); // If it is an Object
// To get benefit of this code Use above function of p in your code.
}

Sort an Array of Objects within Array by value

Basically I'm trying to sort a complex array of Objects within an array:
Array
(
[190515] => stdClass Object
(
[nid] => 15740686
[venue_nid] => 190515
[occurrences] => 1
[this_weeks_occurrences] => 0
[end_date] => 1350853200
[end_date_end_time] => 1350853200
[is_ongoing] => 0
[title] => Wentz Concert Hall and Fine Arts Center
[times] => Array
(
[0] => stdClass Object
(
[nid] => 15740686
[venue_nid] => 190515
[venue_title] => Wentz Concert Hall and Fine Arts Center
[datepart] => 20121021
[occurrences] => 1
[times] => Sun 4:00pm
[end_times] => Sun 4:00pm
[next_year] => 0
[next_month] => 0
[next_week] => 3
[occurrence_date] => 1350853200
)
)
[times_list] => Array
(
[0] => Oct 21 sun 4:00pm
)
)
[31403] => stdClass Object
(
[nid] => 15740686
[venue_nid] => 31403
[occurrences] => 1
[this_weeks_occurrences] => 0
[end_date] => 1350176400
[end_date_end_time] => 1350176400
[is_ongoing] => 0
[title] => KAM Isaiah Israel
[times] => Array
(
[0] => stdClass Object
(
[nid] => 15740686
[venue_nid] => 31403
[venue_title] => KAM Isaiah Israel
[datepart] => 20121014
[occurrences] => 1
[times] => Sat 8:00pm
[end_times] => Sat 8:00pm
[next_year] => 0
[next_month] => 0
[next_week] => 2
[occurrence_date] => 1350176400
)
)
[times_list] => Array
(
[0] => Oct 13 sat 8:00pm
)
)
[33861] => stdClass Object
(
[nid] => 15740686
[venue_nid] => 33861
[occurrences] => 1
[this_weeks_occurrences] => 0
[end_date] => 1350781200
[end_date_end_time] => 1350781200
[is_ongoing] => 0
[title] => Music Institute of Chicago, Nichols Concert Hall
[times] => Array
(
[0] => stdClass Object
(
[nid] => 15740686
[venue_nid] => 33861
[venue_title] => Music Institute of Chicago, Nichols Concert Hall
[datepart] => 20121021
[occurrences] => 1
[times] => Sat 8:00pm
[end_times] => Sat 8:00pm
[next_year] => 0
[next_month] => 0
[next_week] => 3
[occurrence_date] => 1350781200
)
)
[times_list] => Array
(
[0] => Oct 20 sat 8:00pm
)
)
)
I need to sort by occurrence_date and ensure that the data in the top Object (e.g.190515) doesn't become corrupted with other objects and to include the possibility that there could be a 2nd occurrence_date for the "times" [array] of Objects.
I've seen similar sort arrays of objects by field here, but not with the depth of the array/object. I tried using usort but I don't think my syntax to the value is correct.
Basically what I tried.
function cmp($x, $y) {
if ($x->occurrence_date > $y->occurrence_date) {
return 1; }
else {
return -1; }
}
usort($node->timeout_events_schedule->venues, 'cmp');
Thanks in advance
How about:
function compare($x,$y)
{
if($x->times[0]->occurrence_date == $y->times[0]->occurrence_date)
return 0;
elseif($x->times[0]->occurrence_date < $y->times[0]->occurrence_date)
return -1;
else
return 1;
}
uasort($your_array,'compare');
uasort() preserve your keys, unlike usort()
http://www.php.net/manual/en/function.uasort.php
Few tips to help you solve your problem:
you will need uasort function, to preserve associative keys
You can not access occurrence_date key directly from $x o r $y, you will need $x->times[0]->occurence_date
Before doing comparison, iterate through $x->times just to check if there are more entries, pick one that suits your needs.
since occurence_date is a number you don't have to use string comparison function
Good luck :)

php merging arrays

In the multidimensional array below, I would like to merge arrays that have the same merge_id. I'm not sure "merge" is the right word: in the example below, array['0'] should become array['0'] with in it array['0']['0'] and array['0']['1'], the latter being equal to array['1']. I hope this makes sense ...
The array comes out of the db sorted on merge_id so arrays with matching merge_id are always "next to" each other, and there will only ever be 2 with the same merge_id
As I loop through the array I know I need to keep a variable that is always equal to the previous merge_id and if there is a match between previous and current, then merge.
Array
(
[0] => Array
(
[client_id] => 5
[company_name] => company111_name
[id] => 3
[fee] => 111
[year] => 2009
[quarter] => 3
[date_inserted] => 1264948583
[description] => 2009 - Q3
[fee_type] =>
[merge_id] => a87ff679a2f3e71d9181a67b7542122c
[total_paid] => 0
[total_remainder] => 0
)
[1] => Array
(
[client_id] => 5
[company_name] => company111_name
[id] => 6
[fee] => 55.5
[year] => 2010
[quarter] => 2
[date_inserted] => 1264949470
[description] => 2010 - Q2
[fee_type] =>
[merge_id] => a87ff679a2f3e71d9181a67b7542122c
[total_paid] => 0
[total_remainder] => 0
)
[2] => Array
(
[client_id] => 5
[company_name] => company111_name
[id] => 4
[fee] => 111
[year] => 2009
[quarter] => 4
[date_inserted] => 1264948583
[description] => 2009 - Q4
[fee_type] =>
[merge_id] =>
[total_paid] => 0
[total_remainder] => 0
)
[3] => Array
(
[client_id] => 5
[company_name] => company111_name
[id] => 7
[fee] => 55.5
[year] => 2010
[quarter] => 3
[date_inserted] => 1264949470
[description] => 2010 - Q3
[fee_type] =>
[merge_id] =>
[total_paid] => 0
[total_remainder] => 0
)
)
Code
$merger = $data['search']['0']['merge_id'];
$i = 0;
foreach($data['search'] as $fee)
{
if($fee['merge_id'] == $merger)
{
//bump up & merge arrays
???
}
$merger = $fee['merge_id'];
$i++;
}
You can use the ID as key to put all items with the same ID in the same array:
$merged = array();
foreach ($data['search'] as $fee) {
if ($fee['merge_id'] == '') {
continue;
}
if (!isset($merged[$fee['merge_id']])) {
$merged[$fee['merge_id']] = array();
}
$merged[$fee['merge_id']][] = $fee;
}
$merged = array_values($merged);
Notice that this will skip the items with an empty merge ID. You could also use a default merge ID in that case by replacing continue; with $fee['merge_id'] = 0;.
foreach($array as $p)
$result[$p['merge_id']][] = $p;

Categories