How to sum multidimensional array values then grouping with date as my code.
If any PHP code what should I try please tell me.
Please see the array code:
$array = array (
0 => array(
'date' => '2015-02-06 10:42:39',
'visit' => 1,
'bounce' => 0
),
1 => array(
'date' => '2015-02-06 13:23:21',
'visit' => 1,
'bounce' => 1
),
2 => array(
'date' => '2015-02-07 04:11:42',
'visit' => 1,
'bounce' => 1
),
3 => array(
'date' => '2015-02-08 11:35:28',
'visit' => 1,
'bounce' => 1
),
4 => array(
'date' => '2015-02-08 15:12:09',
'visit' => 1,
'bounce' => 1
),
5 => array(
'date' => '2015-02-09 15:12:09',
'visit' => 1,
'bounce' => 0
),
);
The result I expect must be when I do foreach:
date visit bounce
2015-02-06 2 1
2015-02-07 1 1
2015-02-08 2 2
2015-02-09 1 0
Here is the code what I've tried. But it just return the date count only.
$items = array_column($array, 'date');
$preg = preg_quote('2015-02-06', '~');
$result = preg_grep('~' . $preg . '~', $items);
echo 'Date <br/>' . count($result);
Please help, thank you in advanced.
Solution using array_walk, substr and array_values functions:
$date_keys = [];
array_walk($array, function($v) use(&$date_keys){
$datePart = $v['date'] = substr($v["date"], 0, 10);
if (isset($date_keys[$datePart])) {
$date_keys[$datePart]['visit'] += $v['visit'];
$date_keys[$datePart]['bounce'] += $v['bounce'];
} else {
$date_keys[$datePart] = $v;
}
});
print_r(array_values($date_keys));
The output:
Array
(
[0] => Array
(
[date] => 2015-02-06
[visit] => 2
[bounce] => 1
)
[1] => Array
(
[date] => 2015-02-07
[visit] => 1
[bounce] => 1
)
[2] => Array
(
[date] => 2015-02-08
[visit] => 2
[bounce] => 2
)
[3] => Array
(
[date] => 2015-02-09
[visit] => 1
[bounce] => 0
)
)
You can create a new array:
$newArr = [];
foreach($array as $arr){
$d = (new DateTime($arr['date']))->format('Y-m-d');
$newArr[$d] = [
"visit" => isset($newArr[$d]['visit']) ? $newArr[$d]['visit'] += $arr['visit'] : $arr['visit'],
"bounce" => isset($newArr[$d]['bounce']) ? $newArr[$d]['bounce'] += $arr['bounce'] : $arr['bounce']
];
}
echo "<pre>";
var_dump($newArr);
echo "</pre>";
Above returns a nice formatted array which you can easily read out in the example you posted:
array(4) {
["2015-02-06"]=>
array(2) {
["visit"]=>
int(2)
["bounce"]=>
int(1)
}
["2015-02-07"]=>
array(2) {
["visit"]=>
int(1)
["bounce"]=>
int(1)
}
["2015-02-08"]=>
array(2) {
["visit"]=>
int(2)
["bounce"]=>
int(2)
}
["2015-02-09"]=>
array(2) {
["visit"]=>
int(1)
["bounce"]=>
int(0)
}
}
You could merge your entries like this:
$items = [];
foreach ($array as $value) {
$date = substr($value['date'], 0, 10);
if (!isset($items[$date]) {
$items[$date] = [
'date' => $date,
'visit' => 0,
'bounce' => 0
];
}
$items[$date]['visit'] += $value['visit'];
$items[$date]['bounce'] += $value['bounce'];
}
By using date as a key in the $items array, we make sure we sum up the visit and bounce for each date instead of appending them.
If you'd ever want to get rid of the keys, you can simply use array_values.
If your array is called $myArray, and the new array your creating is $myDateArray:
$myDateArray = array();
foreach ($myArray as $value)
{
list($date_string, $other) = explode(" ", $value['date']);
if (array_key_exists($date_string, $myDateArray))
{
//adding the visits and bounces
$myDateArray[$date_string]['visit'] = $myDateArray[$date_string]['visit'] + $value['visit'];
$myDateArray[$date_string]['bounce'] = $myDateArray[$date_string]['bounce'] + $value['bounce'];
}
else
{
//putting the first values (of the key $date_string) into $myDateArray
array_push($myDateArray, array($date_string, $value['visit], $value['bounce']));
}
}
Let me know if that worked for you!
The code creates a new array which contains the summed result of your array.
$resultArray = [];
foreach($array as $row){
$dateObj = DateTime::createFromFormat('Y-m-d H:i:s', $row['date']);
$key = $dateObj->format('Y-m-d');
if(!array_key_exists($key, $resultArray)){
$resultArray[$key] = ['visit' => $row['visit'], 'bounce' => $row['bounce']];
}
else {
$resultArray[$key]['visit'] += $row['visit'];
$resultArray[$key]['bounce'] += $row['bounce'];
}
}
Result:
array (size=4)
'2015-02-06' =>
array (size=2)
'visit' => int 2
'bounce' => int 1
'2015-02-07' =>
array (size=2)
'visit' => int 1
'bounce' => int 1
'2015-02-08' =>
array (size=2)
'visit' => int 2
'bounce' => int 2
'2015-02-09' =>
array (size=2)
'visit' => int 1
'bounce' => int 0
Does this do the trick ?
<?php
$array = array (
0 => array(
'date' => '2015-02-06 10:42:39',
'visit' => 1,
'bounce' => 0
),
1 => array(
'date' => '2015-02-06 13:23:21',
'visit' => 1,
'bounce' => 1
),
2 => array(
'date' => '2015-02-07 04:11:42',
'visit' => 1,
'bounce' => 1
),
3 => array(
'date' => '2015-02-08 11:35:28',
'visit' => 1,
'bounce' => 1
),
4 => array(
'date' => '2015-02-08 15:12:09',
'visit' => 1,
'bounce' => 1
),
5 => array(
'date' => '2015-02-09 15:12:09',
'visit' => 1,
'bounce' => 0
),
);
$results = [];
foreach($array as $e)
{
$date = explode(' ',$e['date'])[0] ;
if(!isset($results[$date]))
$results[$date] = ['visit'=>0 , 'bounce'=>0] ;
$results[$date]['visit'] += $e['visit'];
$results[$date]['bounce'] += $e['bounce'];
}
print_r($results);
Technique/ Mechnism
$result = array();
$items = array_column($array, 'date');
for($i=0; $i < count($items); $i++){
$date = date("Y-m-d", strtotime($items[$i]));
$result[$date][0] += $array[$i]['visit'];
$result[$date][1] += $array[$i]['bounce'];
}
Result
Please design your output as required.
echo "date visit bounce<br/>";
foreach($result as $key => $value){
echo $key." ".$value[0]." ".$value[1]."<br/>";
}
Output
date visit bounce
2015-02-06 2 1
2015-02-07 1 1
2015-02-08 2 2
2015-02-09 1 0
Related
I have a multi array that has some duplicated values that are same by payment_name ( payment_name is an element )
I want to sum quantity of each array that has same payment_name and display the amount as one. For now the sum comes as array of all amounts. Any assistance will be highly appreciated.
var_export($num) results looks like this
array(
'items' => array (
'2020-08-04' => array (
0 => array (
0 => array (
'payment_name' =>'Cash',
'amount_paid' => array (
0 => '0',
),
),
),
1 => 0,
),
'2020-08-05' => array (
0 => array(
0 => array (
'payment_name' => 'Cash',
'amount_paid' => array (
0 => '0',
1 => '0',
2 => '165',
),
),
1 => array (
'payment_name' => 'Mpesa',
'amount_paid' => array (
0 => '0',
1 => '0',
2 => '165',
),
),
),
1 => 165,
),
My expected array should be like this, the amount paid should be the total, not an array of all amounts:
"2020-08-05" => array:2 [▼
0 => array:2 [▼
0 => array:2 [▼
"payment_name" => "Cash"
"amount_paid" => "0"
]
1 => array:2 [▼
"payment_name" => "Mpesa"
"amount_paid" => "165"
]
]
]
1 => 165
]
My code is as below
$requests = $builder->get()->groupBy('date');
$num = $requests->map(function ($row) {
$result = array();
$ttl = $row->sum('amount_paid');
$row = $row->toArray();
$names = array_column($row, 'payment_name');
$amount = array_column($row, 'amount_paid');
$unique_modes = array_unique($names);
foreach ($unique_modes as $name) {
$this_keys = array_keys($names, $name);
$qty = array_sum((array_intersect_key($amount, array_combine($this_keys, $this_keys))));
$result[] = array("payment_name"=>$name, "amount_paid"=>$amount);
}
return [$result, $ttl ];
});
return $num;
I fixed my problem using the code below:
$num = $requests->map(function ($row) {
$result = array();
$ttl = $row->sum('amount_paid');
$row = $row->toArray();
$final_array = [];
foreach($row as $arr){
$final_array[$arr['payment_name']]['payment_name'] = $arr['payment_name'];
$final_array[$arr['payment_name']]['amount_paid'] = (isset($final_array[$arr['payment_name']]['amount_paid']))? $final_array[$arr['payment_name']]['amount_paid']+$arr['amount_paid'] : $arr['amount_paid'];
}
$final_array = array_values($final_array);
return [$final_array, $ttl];
});
I have an array with some repeating string values. How to replace these string values (as a whole, because some words are repeated in others strings) with corresponding specific numeric values, as bellow?
deloc = 1
foarte puţin = 2
mediu = 3
mult = 4
foarte mult = 5
This is the array (example):
array = (
"tensionat" => "mediu",
"trist" => "mult",
"melancolic" => "deloc",
"fara_speranta" => "foarte puțin",
"nefolositor"] => "deloc",
"ingrijorat" => "foarte mult",
"amarat" => "deloc",
"anxios" => "mediu"
);
How can this
Try this
$data = array (
"tensionat" => "mediu",
"trist" => "mult",
"melancolic" => "deloc",
"fara_speranta" => "foarte puțin",
"nefolositor" => "deloc",
"ingrijorat" => "foarte mult",
"amarat" => "deloc",
"anxios" => "mediu"
);
$repl = array (
'deloc' => 1,
'foarte puţin' => 2,
'mediu' => 3,
'mult' => 4,
'foarte mult' => 5,
);
$result = array ();
foreach ($data as $key => $value) {
$result[$key] = !empty($repl[$value]) ? $repl[$value] : $value;
}
print_r($result);
Output:
Array
(
[tensionat] => 3
[trist] => 4
[melancolic] => 1
[fara_speranta] => foarte puțin
[nefolositor] => 1
[ingrijorat] => 5
[amarat] => 1
[anxios] => 3
)
I have a multi dimensional array. I need to sum up the distance values with same 'driver' and 'date' keys
Input :
$firstArr = array(
0 =>array('driver'=>'xxxx',
'distance' => 100,
'vehicle' => 1,
'date' => '2019-10'),
1=>array('driver'=>'xxxx',
'distance' => 200,
'vehicle' => 2,
'date' => '2019-10'),
2=>array('driver'=>'yyyy',
'distance' => 100,
'vehicle' => 3,
'date' => '2019-10'));
Output Expected :
$finalArr = array(
0 =>array('driver'=>'xxxx',
'distance' => 300,
'vehicle' => '1,2',
'date' => '2019-10'),
1=>array('driver'=>'yyyy',
'distance' => 100,
'vehicle' => 3,
'date' => '2019-10'));
I tried below code. But the output is a datewise array.
$subArr = array();
foreach($firstArr as $key => $val){
$subArr[$val['driver']][$val['date']]['distance'] += $val['distance'];
$subArr[$val['driver']][$val['date']]['vehicle'] .= $val['vehicle'].',';
$subArr[$val['driver']][$val['date']]['date'] = $val['date'];
$subArr[$val['driver']][$val['date']]['driver'] = $val['driver'];
}
$result = array_values($subArr);
You can use the dirver and date as a key, Demo
$result = [];
foreach($array as $v){
$key = $v["driver"] . "_" . $v["date"];
if(isset($result[$key])){
$result[$key]["distance"] += $v["distance"];
}else{
$result[$key] = $v;
}
}
$result = array_values($result);
You can also use array_reduce to sum up the distance and the vehicles by driver and date.
With the help of array_combine we can set the initial array if not exists for each driver date combo and then do the processing of the required fields.
$keys = array_keys($input[0]);
$result = array_reduce($input, function ($sum, $row) use ($keys) {
$key = $row['driver'] . $row['date'];
$sum[$key] = $sum[$key] ?? array_combine($keys, [$row['driver'], null, null, $row['date']]);
$sum[$key]['distance'] += $row['distance'];
$sum[$key]['vehicle'] .= (($sum[$key]['vehicle']) ? ',': '' ) . $row['vehicle'];
return $sum;
}, []);
Results in:
Array
(
[xxxx2019-10] => Array
(
[driver] => xxxx
[distance] => 300
[vehicle] => 1,2
[date] => 2019-10
)
[yyyy2019-10] => Array
(
[driver] => yyyy
[distance] => 100
[vehicle] => 3
[date] => 2019-10
)
)
I have an array which contains following values.
array(
'dates' => array(
(int) 0 => '2013-04-22',
(int) 1 => '2013-04-23',
),
'publisherName' => array(
(int) 0 => 'Comp1',
(int) 1 => 'Comp2',
),
'loaded' => array(
(int) 0 => (int) 2189,
(int) 1 => (int) 37,
),
'clicks' => array(
(int) 0 => (int) 0,
(int) 1 => (int) 0,
),
'ctr' => array(
(int) 0 => (int) 0,
(int) 1 => (int) 0,
)
)
What I want to produce is getting company based data on different dates like the array below.
How am I able to create an array which is like;
array (
'2013-04-22'=>array(
'publisherName'=>'Comp1',
'loaded'=>2189,
'clicks'=>0,
'ctr'=>0),
'2013-04-23'=>array(
'publisherName'=>'Comp2',
'loaded'=>37,
'clicks'=>0,
'ctr'=>0)
...
)
Which contains daily stats but which comes from publishername field.
Any ideas?
Here's an example that doesn't rely on any keys, the only requirement is that date is the first array in your original array:
// $array is your original array
$dates = array_shift($array);
$output = array();
foreach ($array as $k => $a) {
foreach ($a as $i => $v) {
$output[$i][$k] = $v;
}
}
$output = array_combine($dates, $output);
Let the initial array be $a and the desired array $b;
Code:
$b = array();
$count = 0;
foreach($a['dates'] as $date) {
$b[$date] = array(
'name' => $a['publisherName'][$count],
'loaded'=> $a['loaded'][$count],
'clicks'=> $a['clicks'][$count],
'ctr'=> $a['ctr'][$count]
);
$count++;
}
Result:
Array
(
[2013-04-22] => Array
(
[name] => Comp1
[loaded] => 2189
[clicks] => 0
[ctr] => 0
)
[2013-04-23] => Array
(
[name] => Comp2
[loaded] => 37
[clicks] => 0
[ctr] => 0
)
)
<?php
$data = $yourarray;
$new = array();
foreach($data['dates'] as $key=>$value) {
$new[$value] = array('name'=>$data['publisherName'][$key],'loaded'=>$data['loaded'][$key],'clicks'=>$data['clicks'][$key],'ctr'=>$data['ctr'][$key]);
}
echo '<pre>';
print_r($new);
?>
$newArr = array();
foreach($data['dates'] as $key=>$value) {
$new[$value] = array('name'=>$data['publisherName'][$key],'loaded'=>$data['loaded'][$key],'clicks'=>$data['clicks'][$key],'ctr'=>$data['ctr'][$key]);
}
echo '<pre>';
print_r($newArr);
$new_arr = your array;
$finalArray = array();
foreach($new_arr['dates'] as $key => $value){
$finalArray[$value] = array(
'publisherName'=>$new_arr['publisherName'][$key],
'loaded'=>$new_arr['loaded'][$key],
'clicks'=>$new_arr['clicks'][$key],
'ctr'=>$new_arr['ctr'][$key]
);
}
Output :
Array
(
[2013-04-22] => Array
(
[publisherName] => Comp1
[loaded] => 2189
[clicks] => 0
[ctr] => 0
)
[2013-04-23] => Array
(
[publisherName] => Comp2
[loaded] => 37
[clicks] => 0
[ctr] => 0
)
)
I have a large array where I basically need to count the number of uniques:
example array
The end result I am looking for something like
$result = array(
'A3D5' => array('P2' => 1, 'P3' => 1, 'P4' => 1, 'total' => 3),
'AE5S' => array('P4' => 1, 'total' => 1)
);
I've tried foreaching through but can't seem to figure out how to sort them into another key, something like $zone = "P{$array['zone']}"; $result[$zone][$prestige]++ or seems to kind of not work or just error.
$array = array(
"denizen" => array
(
"prestige" => 2,
"zone" => "A3D5",
"scope_frag" => 765
),
"생각" => array
(
"prestige" => 4,
"zone" => "A3D5",
"scope_frag" => 135
),
"Ryans" => array
(
"prestige" => 3,
"zone" => "A3D5",
"scope_frag" => 78
),
"지적인" => array
(
"prestige" => 2,
"zone" => "AE5S",
"scope_frag" => 481
)
);
foreach ($array as $group) {
$zones[$group["zone"]][] = $group["prestige"];
}
foreach ($zones as $name => $zone) {
$total = count($zone);
foreach ($zone as $prestige) {
$result[$name]["P".$prestige] += 1;
}
ksort($result[$name]);
$result[$name]["total"] = $total;
}
echo "<pre>";
print_r($result);
echo "</pre>";