PHP push missing weekdays with 0 total into array - php

I need to buildup a graph with total sales for each day for last week, I did not get all 7 days data, rather getting 3 days data from database, I need to push rest of the 4days with total sales 0,
I have the following array of 3 days
Array
(
[0] => Array
(
[SalesDate] => Jun09
[total] => 4
)
[1] => Array
(
[SalesDate] => Jun11
[total] => 2
)
[2] => Array
(
[SalesDate] => Jun14
[total] => 1
)
)
but I need all 7days data from Jun09 to Jun15 like this
Array
(
[0] => Array
(
[SalesDate] => Jun09
[total] => 4
)
[1] => Array
(
[SalesDate] => Jun10
[total] => 0
)
[2] => Array
(
[SalesDate] => Jun11
[total] => 2
)
[3] => Array
(
[SalesDate] => Jun12
[total] => 0
)
[4] => Array
(
[SalesDate] => Jun13
[total] => 0
)
[5] => Array
(
[SalesDate] => Jun14
[total] => 1
)
[6] => Array
(
[SalesDate] => Jun15
[total] => 0
)
)
I have tried with following code, but not getting the required data.
<?php
$sales =array(array('SalesDate' => 'Jun09',
'total' => 4
),
array
(
'SalesDate' => 'Jun11',
'total' => 2
),
array
(
'SalesDate' => 'Jun14',
'total' => 1
)
);
$final_array = array();
foreach($sales as $sale)
{
for($i=7;$i>0;$i--)
{
$current_weeks =[];
if($sale['SalesDate'] ==date('Md', strtotime("-".$i." days")))
{
$week_days['SalesDate'] = $sale['SalesDate'];
$week_days['total'] = $sale['total'];
}
else
{
$week_days['SalesDate'] = date('Md', strtotime("-".$i." days"));
$week_days['total'] = 0;
}
$final_array[] =$week_days;
}
}

You could first create a 'skeleton' array that matches your source array $arr, but with all the previous seven days $prevSevenDays. The date format matches the source array's, the totals are all set to 0.
// build empty skeleton
$prevSevenDays = [];
for ($i = 7; $i > 0; $i--) {
$prevSevenDays[$i]['SalesDate'] = date('Md', strtotime("-$i days"));
$prevSevenDays[$i]['Total'] = 0;
}
All you have to do is cycle through this array to replace the entries with available data in your source array $arr.
foreach ($arr as $sales) {
foreach ($prevSevenDays as $key => $day) {
if ($sales['SalesDate'] === $day['SalesDate']) $prevSevenDays[$key]['Total'] = $sales['Total'];
}
}
demo

Related

Get same index value of an array repeated time, based on a variable in php

We have an array in PHP like below:
Array
(
[0] => Array
(
[id] => 29
[name] => Testing1
)
[1] => Array
(
[id] => 30
[name] => Testing2
)
[2] => Array
(
[id] => 31
[name] => Testing3
)
)
We also have a variable $getvalue . We want to create a function (we will use the function in for loop) in which we pass above array and $getvalue. If $getvalue = 2 it should return key[0] 2 time, key[1] 2 time and key[2] 2 time like below.
[0] => Array
(
[id] => 29
[name] => Testing1
)
[0] => Array
(
[id] => 29
[name] => Testing1
)
[1] => Array
(
[id] => 30
[name] => Testing2
)
[1] => Array
(
[id] => 30
[name] => Testing2
)
[2] => Array
(
[id] => 31
[name] => Testing3
)
[2] => Array
(
[id] => 31
[name] => Testing3
)
If $getvalue = 1 it should return key[0] 1 time, key[1] 1 time and key[2] 1 time like below.
[0] => Array
(
[id] => 29
[name] => Testing1
)
[1] => Array
(
[id] => 30
[name] => Testing2
)
[2] => Array
(
[id] => 31
[name] => Testing3
)
Tried :
for($i = 0; $i<=count($array); $i++) {
foreach($array as $key => $val) {
if($i==$getvalue )
{
$a[] = $array[$i+1];
}
else
{
$a[] = $array[$i];
}
}
}
Also tried :
static function abc ($array,$getvalue)
{
foreach ($array as $key => $value) {
for ($i=0; $i <= $getvalue; $i++) {
return $arr[$i];
}
}
}
Each element of input array is added to the return value $getvalue times:
<?php
function repeatify( array $array, int $getvalue ): array {
$out = [];
if($getvalue <= 0) return $out;
foreach( $array as $element ){
foreach( range(0, $getvalue - 1) as $we_actualy_are_not_using_this_var )
$out[] = $element;
# Or alternatively with a `for` loop (i'll comment this out since i prefer an above code):
/*
for (
$we_actualy_are_not_using_this_var = 0;
$we_actualy_are_not_using_this_var < $getvalue;
$we_actualy_are_not_using_this_var++
) {
$out[] = $element;
}
*/
}
return $out;
}
$data = [
[
'id' => 29,
'name' => 'Testing1',
],
[
'id' => 30,
'name' => 'Testing2',
],
[
'id' => 31,
'name' => 'Testing2',
],
];
print '<pre>';
print_r( repeatify( $data, 0 ) );
print_r( repeatify( $data, 1 ) );
print_r( repeatify( $data, 2 ) );

Increment count for value in foreach loop PHP

I am trying to count the instances of rfid from one array to insert into another array so I can use this data to create charts.
At the moment my code is as follows
if ($message == "Broken" && $message_type == "BreakBeam" && $previous==$cat_id) {
$total = 1;
$splitTimeStamp = explode(" ",$eventtime);
$date = $splitTimeStamp[0];
$time = $splitTimeStamp[1];
$events[$c]['date'] = $date;
$events[$c]['device'] = $device;
$events[$c]['time']= $time;
$events[$c]['rfid']= $previous;
$events[$c]['count']=$total;
$c++;
}
}
$a = array();
$i=0;
foreach($events as $event){
if(isset($a[$event['rfid']])){
$a['rfid_id'][$event['rfid']]++;
}else{
$a['rfid_id'][$event['rfid']]=1;
}
if(isset($a[$event['date']])){
$a['dateinsert'][$event['date']]++;
}else{
$a['dateinsert'][$event['date']] =1;
}
}
$rfid = array();
// those are the ones we're going to put in!
foreach($a as $key => $count) {
foreach($count as $eventdetails['rfid_id'] => $event){
// so $key is the [rfid] key of the entry and $count is the count (all 1's?) in it
if (isset($rfid[$key])) {
$rfid[$key]+=$event;
}
else {
$rfid[$key]=$event;
}
}
}
Which outputs as follows :
Array
(
[0] => Array
(
[date] => 2020-09-17
[device] => 2
[time] => 15:51:37
[rfid] => 23641
[count] => 1
)
[1] => Array
(
[date] => 2020-09-17
[device] => 2
[time] => 15:52:20
[rfid] => 5609
[count] => 1
)
[2] => Array
(
[date] => 2020-09-17
[device] => 2
[time] => 15:53:23
[rfid] => 5609
[count] => 1
)
[3] => Array
(
[date] => 2020-09-17
[device] => 2
[time] => 16:02:44
[rfid] => 5609
[count] => 1
)
)
Array
(
[rfid_id] => Array
(
[23641] => 1
[5609] => 1
)
[dateinsert] => Array
(
[2020-09-17] => 1
)
)
Array
(
[rfid_id] => 2
[dateinsert] => 1
)
Ideally, I would like to achieve the following :
Array
(
[rfid_id] => Array
(
[23641] => 1
[5609] => 3
)
[dateinsert] => Array
(
[2020-09-17] => 1
)
)
or something to that effect, where I can look at the date, rfid codes and the time each was read on that date.
You simply missing the path in the assignment loop.
Same goes for rfid and date so I just explain on rfid.
You check the isset on one path but is not exist set on another - this cause the path to never exist - that why you keep getting 1's.
Look at:
foreach($events as $event){
if(isset($a[$event['rfid']])){
$a['rfid_id'][$event['rfid']]++;
} else {
$a['rfid_id'][$event['rfid']]=1;
}
}
Notice $a[$event['rfid']] is NOT the same as $a['rfid_id'][$event['rfid']].
You should change the if statement to be: if (isset($a['rfid_id'][$event['rfid']))

Group subsets of data in 3-level array by identifying column

I've this type of array in PHP:
Array(
[100] => Array(
[1] => Array (
[AVA_Date] => 2019-04-18
[ROO_Id] => 100
[RAT_Id] => 9
)
[2] => Array (
[AVA_Date] => 2019-04-20
[ROO_Id] => 100
[RAT_Id] => 10
)
[4] => Array (
[AVA_Date] => 2019-04-21
[ROO_Id] => 100
[RAT_Id] => 10
)
[7] => Array (
[AVA_Date] => 2019-04-22
[ROO_Id] => 100
[RAT_Id] => 9
)
)
)
I would like to merge items on ROO_Id and RAT_Id.
Then, for the AVA_Date, I need to list them under a new array in the current array.
So, the desired output is:
Array(
[100] => Array(
[0] => Array (
[AVA_Date] => Array (
[0] => 2019-04-18
[1] => 2019-04-22
)
[ROO_Id] => 100
[RAT_Id] => 9
)
[1] => Array (
[AVA_Date] => Array (
[0] => 2019-04-20
[1] => 2019-04-21
)
[ROO_Id] => 100
[RAT_Id] => 10
)
)
)
Here what I have tried:
$newArrOtherRooms = array_reduce($newArr, function($acc, $val) {
$room = array_search($val['ROO_Id'], array_column($acc, 'ROO_Id'));
$rate = array_search($val['RAT_Id'], array_column($acc, 'RAT_Id'));
if($rate == $room && $room > -1) {
array_push($acc[$room]['AVA_Date'], $val['AVA_Date']);
}
else {
$new_arr = $val;
$new_arr['AVA_Date'] = [$val['AVA_Date']];
array_push($acc, $new_arr);
}
return $acc;
},[]);
But it doesn't work like I want.
There are a couple of issues with your code. Firstly, you need to wrap the array_reduce with a foreach over the outer level of $newArr. Secondly, your call to array_search doesn't consider the fact that a ROO_Id or RAT_Id value might exist more than once in the array, as it only returns the first key at which it finds the value. To work around this, you can use array_keys to get an array of key values for each ROO_Id and RAT_Id value, and then take the intersection of those two arrays using array_intersect to see if both are present in the same element. If so, you update that element, otherwise you create a new one:
foreach ($newArr as $key => $array) {
$newArrOtherRooms[$key] = array_reduce($array, function($acc, $val) {
$room = array_keys(array_column($acc, 'ROO_Id'), $val['ROO_Id']);
$rate = array_keys(array_column($acc, 'RAT_Id'), $val['RAT_Id']);
$common = array_intersect($room, $rate);
if(!empty($common)) {
array_push($acc[current($common)]['AVA_Date'], $val['AVA_Date']);
}
else {
$new_arr = $val;
$new_arr['AVA_Date'] = [$val['AVA_Date']];
array_push($acc, $new_arr);
}
return $acc;
},[]);
}
print_r($newArrOtherRooms);
Output:
Array(
[100] => Array(
[0] => Array (
[AVA_Date] => Array (
[0] => 2019-04-18
[1] => 2019-04-22
)
[ROO_Id] => 100
[RAT_Id] => 9
)
[1] => Array (
[AVA_Date] => Array (
[0] => 2019-04-20
[1] => 2019-04-21
)
[ROO_Id] => 100
[RAT_Id] => 10
)
)
)
Demo on 3v4l.org
There is absolutely no reason to be making all of those iterated function calls.
Use a nested loop to iterate the subset of data for each room, group on the room "rate id", and push all "available date" values into a subarray in the respective group. When the subset of data is fully iterated, push its grouped data into the result array.
Code: (Demo)
$result = [];
foreach ($newArr as $rooId => $rows) {
$groups = [];
foreach ($rows as $row) {
if (!isset($groups[$row['RAT_Id']])) {
$row['AVA_Date'] = (array) $row['AVA_Date'];
$groups[$row['RAT_Id']] = $row;
} else {
$groups[$row['RAT_Id']]['AVA_Date'][] = $row['AVA_Date'];
}
}
$result[$rooId] = array_values($groups);
}
var_export($result);
Output:
array (
100 =>
array (
0 =>
array (
'AVA_Date' =>
array (
0 => '2019-04-18',
1 => '2019-04-22',
),
'ROO_Id' => 100,
'RAT_Id' => 9,
),
1 =>
array (
'AVA_Date' =>
array (
0 => '2019-04-20',
1 => '2019-04-21',
),
'ROO_Id' => 100,
'RAT_Id' => 10,
),
),
)

Different Arrays convert into multi-dimension array

I want to combine multiple arrays output in single array. Below is the array I am getting when I do this.
print_r($getData_milestone);
I have arrays as below:
[milestone] => Array
(
[0] => milestone 1
[1] => milestone 2
[2] => milestone 3
)
[date] => Array
(
[0] => 10/25/2015
[1] => 10/30/2015
[2] => 11/25/2015
)
[status] => Array
(
[0] => 1
[1] => 1
[2] => 0
)
And I want to get output such as below:
Array
(
[0] => Array
(
[milestone] => milestone 1
[date] => 10/25/2015
[status] => 1
)
[1] => Array
(
[milestone] => milestone 2
[date] => 10/30/2015
[status] => 1
)
[2] => Array
(
[milestone] => milestone 3
[date] => 11/25/2015
[status] => 0
)
)
I have tried by this code
foreach($getData_milestone['milestone'] as $miledata)
{
$allDatamile[$i]=$getData_milestone;
$allDatamile[$i]=$getData_milestone['date'];
$allDatamile[$i]=$getData_milestone['status'];
$i++;
}
Try this out, and let me know the result. It should work.
I am considering the given array as an associative array with keys "milestone", "date" and "status" .. Correct me if I'm wrong.
$outputArray = array();
foreach($givenArray['milestone'] as $key=>$val){
$outputArray[$key]['milestone'] = $val;
$outputArray[$key]['date'] = $givenArray['date'][$key];
$outputArray[$key]['status'] = $givenArray['status'][$key];
}
print_r($outputArray)
try this,
$a["milestone"][] = "milestone 1";
$a["milestone"][] = "milestone 2";
$a["milestone"][] = "milestone 3";
$a["date"][] = "10/25/2015";
$a["date"][] = "10/30/2015";
$a["date"][] = "11/25/2015";
$a["status"][] = "1";
$a["status"][] = "1";
$a["status"][] = "0";
foreach ($a['milestone'] as $key => $val) {
$a1[$key]["milestone"] = $val;
$a1[$key]["date"] = $a['date'][$key];
$a1[$key]["status"] = $a['status'][$key];
}
output is
Array
(
[0] => Array
(
[milestone] => milestone 1
[date] => 10/25/2015
[status] => 1
)
[1] => Array
(
[milestone] => milestone 2
[date] => 10/30/2015
[status] => 1
)
[2] => Array
(
[milestone] => milestone 3
[date] => 11/25/2015
[status] => 0
)
)
array_column (PHP 5 >= 5.5.0) might help -
$keys = array_keys($arr);
// if the number of element increases(to make it more dynamic)
$count = count($arr['milestone']);
$i= 0;
while($i < $count) {
$new[] = array_column($arr, $i);
$i++;
}
foreach($new as $k => $n) {
$new[$k] = array_combine($keys, $n);
}
var_dump($new);
DEMO
Try it out the bellow code
$out= array();
$milestone=array
(
"milestone 1",
"milestone 2",
"milestone 3"
);
$m_date=array
(
"10/25/2015",
"10/25/2015",
"10/25/2015"
);
$status=array
(
0,1,1
);
for($i=0;$i<count($milestone);$i++){
$comArray=array
(
"milestone" => $milestone[$i],
"date" => $m_date[$i],
"status" => $status[$i]
)
$out[]=$comArray;
}
Hope it will solve your problem.

PHP array - Sum value of the same key when key are number [duplicate]

This question already has answers here:
PHP Array Group by one field and Sum up two fields [duplicate]
(2 answers)
Closed 4 months ago.
My situation is similar to this thread :
Associative array, sum values of the same key
However in my case all keys are number.
I would like to reduce / combine array where key 0 is similar and make a sum of all other keys.
Here is my original array :
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 13
[4] => 0
)
[2] => Array
(
[0] => 222032
[1] => 0
[2] => 0
[4] => 15
)
[3] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
[4] => Array
(
[0] => 222032
[1] => 0
[2] => 7
[4] => 0
)
)
and here is the output i need :
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[4] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
)
The solution of other thread is not working because they use the key name and i don't know how i can adapt this to my situation.
Please if you can give me an example of working solution.
REPLY :
For now i try something like that : Take from other thread
$sum = array_reduce($data, function ($a, $b) {
if (isset($a[$b[0]])) {
$a[$b[0]]['budget'] += $b['budget'];
}
else {
$a[$b[0]] = $b;
}
return $a;
});
But this example look is only for key named budget but in my case is number and i have 3 key [1] [2] [3] how can't sum key 1,2,4 where key 0 is similar
This should work for you:
Basically I just loop through your array and check if there is already an element in $result with the key of the first element of $v. If not I initialize it with an array_pad()'ed array of 0's + the current array of the iteration of the foreach loop.
And after this I loop through each element of $v expect the first one and add it to the result array.
At the end I just reindex the result array with array_values().
<?php
foreach($arr as $v){
if(!isset($result[$v[0]]))
$result[$v[0]] = array_pad([$v[0]], count($v), 0);
$count = count($v);
for($i = 1; $i < $count; $i++)
$result[$v[0]][$i] += $v[$i];
}
$result = array_values($result);
print_r($result);
?>
output:
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[3] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[3] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[3] => 0
)
)
try this
$data = Array
(
0 => Array
(
0 => 93042,
1 => 3,
2 => 0,
4 => 0,
),
1 => Array
(
0 => 222032,
1 => 0,
2 => 13,
4 => 0,
),
2 => Array
(
0 => 222032,
1 => 0,
2 => 0,
4 => 15,
),
3 => Array
(
0 => 152963,
1 => 45,
2 => 0,
4 => 0,
),
4 => Array
(
0 => 222032,
1 => 0,
2 => 7,
4 => 0,
),
);
var_dump($data);
// grouping
$tab1 = array();
foreach ($data as $e) {
if (!isset($tab1[$e[0]])) {
$tab1[$e[0]] = array();
}
$tab1[$e[0]][] = $e;
}
//var_dump($tab1);
// summing
$tabSum = array();
foreach ($tab1 as $id => $t) {
foreach ($t as $e) {
unset($e[0]);
if (!isset($tabSum[$id])) {
$tabSum[$id] = $e;
} else {
foreach ($e as $key => $value) {
$tabSum[$id][$key] += $value;
}
}
}
}
var_dump($tabSum);

Categories