Sum of array for same values - php

I have this array:
Array (
[0] => Array (
[TaxeName] => TPS
[TaxeAmount] => 7
[Price] => 14
)
[1] => Array (
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 10
)
[2] => Array (
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 18
)
)
How I can get another array:
- Grouping the TaxeName and the TaxeAmount and
- Making the sum of the amount Price ?
Like this:
Array (
[0] => Array (
[TaxeName] => TPS
[TaxeAmount] => 7
[Price] => 14
)
[1] => Array (
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 28
)
)

It can be done with a nested foreach:
$original = array(.......); // your current array
$newArr = array();
foreach($original as $origVal){
$exists = false;
foreach($newArr as $key => $newVal){
if($newVal['TaxeName'] == $origVal['TaxeName']){
$newArr[$key]['Price'] += $origVal['Price'];
$exists = true;
break;
}
}
if(!$exists){
$newArr[] = $origVal;
}
}
Outputs
Array
(
[0] => Array
(
[TaxeName] => TPS
[TaxeAmount] => 7
[Price] => 14
)
[1] => Array
(
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 28
)
)

Something like this maybe:
$final = array();
foreach ($arr as $subarr)
{
if (!isset($final[$subarr['TaxeName']]))
{
$final[$subarr['TaxeName']] = array('Price' => 0);
}
$final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeAmount'];
$final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeName'];
$final[$subarr['TaxeName']]['Price'] = $final[$subarr['TaxeName']]['Price'] + $subarr['Price'];
}
The idea is to make a new array with the values that you need and initializing it with the price set to 0 so you can increment it in the foreach

You can do it like this also:
<?php
// Source
$myData = array(
array(
'TaxeName' => 'TPS',
'TaxeAmount' => 7,
'Price' => 14,
),
array(
'TaxeName' => 'TVQ',
'TaxeAmount' => 9.975,
'Price' => 10,
),
array(
'TaxeName' => 'TVQ',
'TaxeAmount' => 9.975,
'Price' => 18,
)
);
// Helper Function
function parseData($data)
{
$parsedData = array();
if (is_array($data)) {
foreach ($data as $dataItem) {
if (!array_key_exists($dataItem['TaxeName'], $parsedData)) {
$parsedData[$dataItem['TaxeName']] = array(
'TaxeName' => $dataItem['TaxeName'],
'TaxeAmount' => $dataItem['TaxeAmount'],
'Price' => floatval($dataItem['Price'])
);
} else {
$parsedData[$dataItem['TaxeName']]['Price'] += floatval($dataItem['Price']);
}
}
}
return array_values($parsedData);
}
// Test
$parsed_data = parseData($myData);
var_dump($parsed_data);
?>
Outputs:

Just use this function, input is your array, output is the array you required:
function calculate(array $input){
$output = [];
foreach ($input as $v){
if (array_key_exists($v['TaxeName'], $output)){
$output[$v['TaxeName']]['Price'] += $v['Price'];
} else {
$output[$v['TaxeName']] = $v;
}
}
return array_values($output);
}

I know that solutions with external classes are not welcome here on SO. I'm showing this just to illustrate the "Grouping the TaxeName and the TaxeAmount" task.
//use class tablearray from https://github.com/jspit-de/tableArray
$data = [
['TaxeName' => 'TPS', 'TaxeAmount' => 7, 'Price' => 14],
['TaxeName' => 'TVQ', 'TaxeAmount' => 9.975, 'Price' => 10],
['TaxeName' => 'TVQ', 'TaxeAmount' => 9.975, 'Price' => 18],
['TaxeName' => 'TVQ', 'TaxeAmount' => 19.975, 'Price' => 23]
];
$newData = tableArray::create($data)
->filterGroupSum('Price',['TaxeName','TaxeAmount'])
->fetchAll()
;
echo '<pre>';
var_export($newData);
Output:
array (
0 =>
array (
'TaxeName' => 'TPS',
'TaxeAmount' => 7,
'Price' => 14,
),
1 =>
array (
'TaxeName' => 'TVQ',
'TaxeAmount' => 9.975,
'Price' => 28,
),
2 =>
array (
'TaxeName' => 'TVQ',
'TaxeAmount' => 19.975,
'Price' => 23,
),
)

Related

multidimensional array php - sum values with same groupRange

I will try to explain my problem in small examples:
I have a multidimensional array that represents data from the database, lets's say the input looks like this:
Array
(
[0] => Array
(
[groupRange] => 20-25
[value] => 12
[followersFemaleRate] => 12
[followersMaleRate] => 14
)
[1] => Array
(
[groupRange] => 30-44
[value] => 32
[followersFemaleRate] => 17
[followersMaleRate] => 3
)
[2] => Array
(
[groupRange] => 30-44
[value] => 88
[followersFemaleRate] => 17
[followersMaleRate] => 3
)
)
What I want? To sum value, followersFemaleRate, followersMaleRate with the same groupRange, so the output should be this:
Array
(
[0] => Array
(
[groupRange] => 20-25
[value] => 12
[followersFemaleRate] => 12
[followersMaleRate] => 14
)
[1] => Array
(
[groupRange] => 30-44
[value] => 120
[followersFemaleRate] => 34
[followersMaleRate] => 6
)
)
My code:
$RangeArray = [];
foreach($dbProfile->getData() as $d) {
foreach ($d->getGroupPercentages() as $x){
$ageRangeSingleArray['groupRange'] = $x->getGroupRange();
$ageRangeSingleArray['value'] = $x->getValue();
$ageRangeSingleArray['followersFemaleRate'] = $x->getFollowerGenderFemale();
$ageRangeSingleArray['followersMaleRate'] = $x->getFollowerGenderMale();
$RangeArray [] = $ageRangeSingleArray;
}
}
However im stuck, my idea is to first check if groupRage already exists, if yes, sum values for that range, if not add new element groupRange with values, any help with code?
#Salines solution was good, but I offer a simple solution for the beginners...
Another simple solution to your problem:
$input = [
[
'groupRange' => '20-25',
'value' => 12,
'followersFemaleRate' => 12,
'followersMaleRate' => 14,
],
[
'groupRange' => '30-44',
'value' => 88,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
[
'groupRange' => '30-44',
'value' => 32,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
];
$groupRangeHolder = [];
$output = [];
foreach($input as $item) {
if( ! array_key_exists( $item['groupRange'] , $groupRangeHolder ) )
{
$groupRangeHolder[$item['groupRange']]['value'] = $item['value'];
$groupRangeHolder[$item['groupRange']]['followersFemaleRate'] = $item['followersFemaleRate'];
$groupRangeHolder[$item['groupRange']]['followersMaleRate'] = $item['followersMaleRate'];
}
else
{
$groupRangeHolder[$item['groupRange']]['value'] += $item['value'];
$groupRangeHolder[$item['groupRange']]['followersFemaleRate'] += $item['followersFemaleRate'];
$groupRangeHolder[$item['groupRange']]['followersMaleRate'] += $item['followersMaleRate'];
}
}
$cur = 0;
foreach($groupRangeHolder as $key => $values)
{
$output[$cur]['groupRange'] = $key;
$output[$cur]['value'] = $values['value'];
$output[$cur]['followersFemaleRate'] = $values['followersFemaleRate'];
$output[$cur++]['followersMaleRate'] = $values['followersMaleRate'];
}
echo "<pre>";
print_r($output);
echo "</pre>";
try:
$input = [
[
'groupRange' => '20-25',
'value' => 12,
'followersFemaleRate' => 12,
'followersMaleRate' => 14,
],
[
'groupRange' => '30-44',
'value' => 88,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
[
'groupRange' => '30-44',
'value' => 32,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
];
$groupedArray = [];
foreach( $input as $item ){
$groupedArray[$item['groupRange']]['groupRange'] = $item['groupRange'];
$groupedArray[$item['groupRange']]['value'] = ($groupedArray[$item['groupRange']]['value'] ?? 0) + $item['value'];
$groupedArray[$item['groupRange']]['followersFemaleRate'] = $item['followersFemaleRate'];
$groupedArray[$item['groupRange']]['followersMaleRate'] = $item['followersMaleRate'];
}
$output = array_values($groupedArray);
print_r($output);
output:
Array
(
[0] => Array
(
[groupRange] => 20-25
[value] => 12
[followersFemaleRate] => 12
[followersMaleRate] => 14
)
[1] => Array
(
[groupRange] => 30-44
[value] => 120
[followersFemaleRate] => 17
[followersMaleRate] => 3
)
)

How to get Php multidimensional array same key’s same value’s related total in new array?

Php multidimensional array same key’s same value’s related total in
new array. I have an array of following mentioned. i need new array
as total qty of same item_id. anyone can help would be appreciate.
My Original Array is as following
Array
(
[a] => Array
(
[item] => Array
(
[item_id] => 1
)
[qty] => 0
),
[b] => Array
(
[item] => Array
(
[item_id] => 2
)
[qty] => 35
),
[c] => Array
(
[item] => Array
(
[item_id] => 2
)
[qty] => 15
),
[e] => Array
(
[item] => Array
(
[item_id] => 3
)
[qty] => 20
),
);
I want array Output like following :
Array(
[0] => Array (
[item_id] => 1,
[item_total_qty] => 0,
)
[1] => Array (
[item_id] => 2,
[item_total_qty] => 50,
)
[2] => Array (
[item_id] => 3,
[item_total_qty] => 20,
)
);
Hope it help
$arrays = array(
'a' => array(
'item' => array(
'item_id' => 1
),
'qty' => 0
),
'b' => array(
'item' => array(
'item_id' => 2
),
'qty' => 35
),
'c' => array(
'item' => array(
'item_id' => 2
),
'qty' => 15
),
'd' => array(
'item' => array(
'item_id' => 3
),
'qty' => 20
)
);
$result = array();
foreach ($arrays as $key => $array) {
if (is_array($result) && !empty($result)) {
foreach ($result as $key => $r) {
if ($r['item_id'] == $array['item']['item_id']) {
$result[$key]['item_total_qty'] += $array['qty'];
continue 2;
}
}
$result[] = array(
'item_id' => $array['item']['item_id'],
'item_total_qty' => $array['qty']);
} else {
$result[] = array(
'item_id' => $array['item']['item_id'],
'item_total_qty' => $array['qty']);
}
}
Simple foreach on your original table:
$sorted = array();
foreach ($original as $item) {
$id = $item['item']['item_id'];
$sorted[$id]['item_total_qty'] = $sorted[$id] ? $sorted[$id] + $item['qty'] : item['qty'];
$sorted[$id]['item_id'] = $id;
}
$sorted = array_values($sorted);

Grouping in array

I have following array..I am trying to group this.
Array
(
[0] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I want to group this into
Array
(
[0] => Array
(
[VitalInfo]=>array(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price]=>array(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I tried but it doesn't happen as I want ...any help would be great...Thanx in advance..
try this,
CODE :
foreach($old_array as $key_old => $val_old)
{
foreach($val_old as $key => $val)
{
if(in_array($key, $VitalInfo_array))
{
$new_array[$key_old]['VitalInfo'][$key] = $val;
}
else
{
$new_array[$key_old]['Price'][$key] = $val;
}
}
}
OUTPUT :
Array
(
[0] => Array
(
[VitalInfo] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price] => Array
(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
)
DEMO
i hope it will be helpful.
Simply loop through your array and customize a new array accordingly.
Assuming $array is the original array, and $result is the customized array, try this:
foreach ($array as $k => $arr) {
$result[$k]['VitalInfo'] = array(
'Title' => $arr['Title'],
'ean' => $arr['ean'],
'upc' => $arr['upc'],
'ProductImageName' => $arr['ProductImageName'],
'CdnUri' => $arr['CdnUri'],
'ASIN' => $arr['ASIN']
);
$result[$k]['Price'] = array(
'ListPrice' => $arr['ListPrice'],
'Status' => $arr['Status'],
'ActualPrice' => $arr['ActualPrice'],
'ProductID' => $arr['ProductID']
);
}
Input : $info // Your Original Array
Ouput : $finalArr // Your Required Array
$vitalInfo = array ('Title','ean','upc','ProductImageName','CdnUri','ASIN');
$price = array ('ListPrice','Status','ActualPrice','ProductId');
$finalArr = array();
foreach ($info as $arr) {
$result = array();
foreach($arr as $k => $v){
if(in_array($k,$vitalInfo))
$result['VitalInfo'][$k] = $v;
else if(in_array($k,$price))
$result['Price'][$k] = $v;
}
$finalArr[] = $result;
}
If you are grouping this in php, have a look at these answers.
Or just copy this:
$input = [0 => [
'Title' => 'HoMedics MAN-300',
'ean' => 31262006288,
'upc' => 31262006288,
'ProductImageName' => '',
'CdnUri' => '',
'ASIN' => 'B000050FEU',
'ListPrice' => 129.99,
'Status' => 2,
'ActualPrice' => 129.99,
'ProductID' => 5286728
]];
foreach ($input as $in){
$out['VitalInfo'] = [];
$out['Price'] = [];
foreach ($in as $key => $i){
if (in_array($key, ['Title', 'ean', 'upc', 'ProductImageName', 'CdnUri', 'Asin'])){
$out['VitalInfo'][] = [$key => $i];
} else {
$out['Price'][] = [$key => $i];
}
}
$output[]=$out;
}
echo '<pre>';
var_dump($output);

Get sum of values which have same value for key php array

I have below array,
Array ( [0] => Array ( [report_id] => 1 [amount] => 100.00 [category_name] => Trial1 ) [1] => Array ( [report_id] => 1 [amount] => 150.00 [category_name] => Trial2 ) [2] => Array ( [report_id] => 1 [amount] => 200.00 [category_name] => Trial2 )
What i want to send to have JSON with below format
It will get some of Equal category name and then send it as json.
[{'category_name': 'Trial1', 'Sum':100]}, {'category_name':'Trial2', 'Sum':350]
How can i achieve this?
Was thinking to get foreach loop and then make compare of category_name and use .=+ to get sum? but i lost there,
Thanks,
Try below solution:
<?php
$array = array (
'0' => Array ( 'report_id' => 1, 'amount' => '100.00', 'category_name' => 'Trial1' ) ,
'1' => Array ( 'report_id' => 1, 'amount' => '150.00' ,'category_name' => 'Trial2' ),
'2' => Array ( 'report_id' => 1, 'amount' => '200.00' ,'category_name' => 'Trial2' ) ,
);
$new_array = array();
foreach($array as $a){
if(!isset($new_array[$a['category_name']]['amount'])){
$new_array[$a['category_name']]['amount'] = 0;
}
$new_array[$a['category_name']] = array(
'category_name' => $a['category_name'],
'amount' => $new_array[$a['category_name']]['amount'] + $a['amount'],
);
}
//print_r(array_values($new_array));
echo json_encode(array_values($new_array));
Output
[{"category_name":"Trial1","amount":100},{"category_name":"Trial2","amount":350}]
Possible solution:
$categoriesArray = array();
foreach ($yourArray as $arrayItem) {
if (!isset($categoriesArray[$arrayItem['category_name']])) {
$categoriesArray[$arrayItem['category_name']] = array(
'category_name' => $arrayItem['category_name'],
'sum' => 0
);
}
$categoriesArray[$arrayItem['category_name']]['sum'] += $arrayItem['amount'];
}
$categoriesArray = json_encode(array_values($categoriesArray));
Assuming $input is your array and $output is the JSON string:
$categorysum = [];
array_walk($input, function($el) use (&$categorysum) {
$categorysum += [$el['category_name'] => ['category_name' => $el['category_name'], 'Sum' => 0]];
$categorysum[$el['category_name']]['Sum'] += $el['amount'];
});
$output = json_encode(array_values($categorysum));

Loop and merge if there are the same key

Array ( [0] => Array ( [field_airline] => 18 [title] => FGGH [field_route_location] => Hongkong [field_time] => 01:10 )
[1] => Array ( [field_airline] => 19 [title] => DSSA [field_route_location] => Kuala Lumpur [field_time] => 01:10 ),
[2] => Array ( [field_airline] => 19 [title] => ASAS [field_route_location] => Kuala Lumpur [field_time] => 01:10 )
)
The merge result I want
Array ( [0] => Array ( [field_airline] => 18 [title] => FGGH [field_route_location] => Hongkong [field_time] => 01:10 ),
[1] => Array ( [field_airline] => 19 [title] => array(DSSA,ASAS) [field_route_location] => Kuala Lumpur [field_time] => 01:10)
)
I AM TRYING
<?php
$a= Array ( 0 => Array ( 'field_airline' => 18 ,
'title' => 'FGGH',
'field_route_location' => 'Hongkong',
'field_time' => '01:10'
),
1 => Array ( 'field_airline' => 19 ,
'title' => 'DSSA',
'field_route_location' => 'Kuala Lumpur',
'field_time' => '01:10'
),
2 => Array ( 'field_airline' => 19,
'title' => 'ASAS',
'field_route_location' => 'Kuala Lumpur',
'field_time' => '01:10'
)
);
$b = array();
foreach ($a as $key=>$value){
$b[$value['field_route_location']][] = $value;
}
echo '<pre>';
print_r($b);
echo '</pre>';
?>
function sortByLocation($a, $b)
{
return strcmp($a["field_route_location"], $b["field_route_location"]);
}
$a = Array(
0 => Array('field_airline' => 18,
'title' => 'FGGH',
'field_route_location' => 'Hongkong',
'field_time' => '01:10'
),
1 => Array('field_airline' => 19,
'title' => 'DSSA',
'field_route_location' => 'Kuala Lumpur',
'field_time' => '01:10'
),
2 => Array('field_airline' => 19,
'title' => 'ASAS',
'field_route_location' => 'Kuala Lumpur',
'field_time' => '01:10'
)
);
usort($a, 'sortByLocation'); // sorting array by location
$b = array();
foreach ($a as $key => $value)
{
$title = array();
if (!isset($b[$value['field_route_location']]))
$b[$value['field_route_location']] = $value;
else
{
if (!is_array($b[$value['field_route_location']]['title']))
array_push($title, $b[$value['field_route_location']]['title']);
else
$title = $b[$value['field_route_location']]['title'];
array_push($title, $a[$key]['title']);
$b[$value['field_route_location']]['title'] = $title;
}
}
echo '<pre>';
print_r($b);
echo '</pre>';
Output
Array
(
[Hongkong] => Array
(
[field_airline] => 18
[title] => FGGH
[field_route_location] => Hongkong
[field_time] => 01:10
)
[Kuala Lumpur] => Array
(
[field_airline] => 19
[title] => Array
(
[0] => ASAS
[1] => DSSA
)
[field_route_location] => Kuala Lumpur
[field_time] => 01:10
)
)
foreach ($a as $ka=>&$va)
{
foreach ($a as $kb=>$vb)
{
if ($va['field_airline'] == $vb['field_airline'] && $ka != $kb)
{
if (is_array($va['title']))
{
$va['title'][] = $vb['title'];
}
else
{
$va['title'] = array($va['title'], $vb['title']);
}
// repeat if/else with the other fields if needed
unset($a[$kb]);
}
}
}
Concept:
Create a blank results array. Loop through the given data. For every item, if it does not exist in results array, push it. If it does exist, push the item's title to the results array for that field_airline element.
Code:
$array_result = array();
if ( ! empty($array)){
foreach($array as $item){
// item already exists in results
if (isset($array_result[$item['field_airline']])){
// prepare title
$title = $array_result[$item['field_airline']]['title'];
$title[] = $item['title']; // push into existing array
// replace array of titles
$array_result[$item['field_airline']]['title'] = $title;
}
// encountering for first time
else{
$array_result[$item['field_airline']] = array(
'field_airline' => $item['field_airline'],
'title' => array($item['title']),
'field_route_location' => $item['field_route_location'],
'field_time' => $item['field_time'],
);
}
}
}
$array_result = array_values($array_result); // reset the keys in results
Test Code:
$array = array(
array(
'field_airline' => 18,
'title' => 'FGGH',
'field_route_location' => 'Hongkong',
'field_time' => '01:10',
),
array(
'field_airline' => 19,
'title' => 'DSSA',
'field_route_location' => 'Kuala Lumpur',
'field_time' => '01:10',
),
array(
'field_airline' => 19,
'title' => 'ASAS',
'field_route_location' => 'Kuala Lumpur',
'field_time' => '01:10',
),
);
Try this.
<?php
$arr=array('0' => array('field_airline' => 18,
'title' => 'FGGH',
'field_route_location' => 'Hongkong',
'field_time' => '01:10'),
'1' => array('field_airline' => 19,
'title' => 'DSSA',
'field_route_location' => 'Kuala Lumpur',
'field_time' => '01:10'),
'2' => array('field_airline' => 19,
'title' => 'ASAS',
'field_route_location' => 'Test',
'field_time' => '01:10')
);
$final=array();
$uniqkeys=array(); // to check for unique field_airline
foreach($arr as $key => $subarr)
{
if(!in_array($subarr['field_airline'],$uniqkeys))
{
$uniqkeys[]=$subarr['field_airline'];
$final[$subarr['field_airline']]= $subarr;
}
else
{
// Check if title is not same, add title to array
if($final[$subarr['field_airline']]['title'] != $subarr['title'])
{
$final[$subarr['field_airline']]['title']=array(
$final[$subarr['field_airline']]['title'], $subarr['title']);
}
//Check for location
if($final[$subarr['field_airline']]['field_route_location'] != $subarr['field_route_location'])
{
$final[$subarr['field_airline']]['field_route_location']=array(
$final[$subarr['field_airline']]['field_route_location'], $subarr['field_route_location']);
}
// Check for filed time
if($final[$subarr['field_airline']]['field_time'] != $subarr['field_time'])
{
$final[$subarr['field_airline']]['field_time']=array(
$final[$subarr['field_airline']]['field_time'], $subarr['field_time']);
}
}
}
print_r($final);
?>
Check the working example here(http://codepad.org/UkOZq9gy).

Categories