I have an array which is a lis, how would I sum the revenue from the specific dates? Please see code below or here https://3v4l.org/eUavL
Like this:
2018-10-28-29.02 USD
2018-10-29-34.73 USD
2018-10-30-27.22 USD
== Sum 90.97 USD
Thanks so much from help!!
<?php
$curl_response = '{
"options": {
"ranking_metric": "paid_impressions",
"time_interval": "day",
"report_type": "time",
"filters": {
"pid": "2759"
},
"data_source": "detailed",
"format": "json",
"end_date": "2018-10-28 23:59",
"columns": ["paid_impressions", "revenue"],
"time_zone": "UTC",
"start_date": "2018-10-26 00:00"
},
"api_url": "http://udmserve.com/udm/radalytics_api.cpx?action=report&api_key=xxxx&api_key=xxxx",
"time": 1540989662,
"rows": [{
"paid_impressions": "18136",
"timestamp": "2018-10-26 00:00",
"_combined_val": "",
"ranking_col": "49046",
"revenue": "28.461629999999985",
"rank": "1",
"f0_": ""
}, {
"paid_impressions": "14432",
"timestamp": "2018-10-27 00:00",
"_combined_val": "",
"ranking_col": "49046",
"revenue": "25.707970000000017",
"rank": "1",
"f0_": ""
}, {
"paid_impressions": "16478",
"timestamp": "2018-10-28 00:00",
"_combined_val": "",
"ranking_col": "49046",
"revenue": "29.07676000000002",
"rank": "1",
"f0_": ""
}]
}';
$array = json_decode($curl_response,true);
foreach($array['rows'] as $arr){
echo explode(' ',$arr['timestamp'])[0].'-'.number_format((float)$arr['revenue'], 2, '.', '').' USD'.PHP_EOL;
}
Code also here: https://3v4l.org/eUavL
Just keep a running total as you iterate.
Code: (Demo)
$array = json_decode($curl_response,true);
$sum = 0;
foreach ($array['rows'] as $set) {
$sum += $revenue = number_format((float)$set['revenue'], 2, '.', '');
echo explode(' ', $set['timestamp'])[0] , "-$revenue USD\n";
}
echo "\t== " , number_format((float)$sum, 2, '.', '') , " USD";
Output:
2018-10-26-28.46 USD
2018-10-27-25.71 USD
2018-10-28-29.08 USD
== 83.25 USD
*note, this keeps adding the number_formatted values. If you require higher specificity -- that is, you want to add up the longer float values and then only format the total once at the end, I can code that up too.
Related
I have question, is it possible not to duplicate the array object by looping on it? Right now I used laravel as my backend
I have here my response which is the exchange object duplicate itself.
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
]
Now my goal is to push the exchange without duplication:
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
}
]
Here is what my foreach loop like and how i push the array object.
$myArray = [];
foreach($exchange_check as $primary_array) {
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
array_push($myArray, (object)[
'exchange' => $primary_array,
'exchange_list' => $second_array,
]);
}
}
}
Thanks
You should add exchange data to array only once in first loop:
$myArray = [];
foreach($exchange_check as $primary_array) {
$idx = array_push($myArray, ['exchange' => $primary_array]);
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
//array_push() returns the new number of elements in the array,
//to get currently added array element we should subtract 1 from this number
$myArray[$idx-1]['exchange_list'][] = $second_array;
}
}
}
And in second loop add only exchange_list data to array.
I have the table "orders" from woocommerce.
I filtered and get sorted the elements by status with GET request.
The results are copied to a JSON file.
So now, I want to find the elements with the same "product_id" and their values and summarize them to display in screen so I can print them.
For example:
"product_id": 45329,
"variation_id": 0,
"quantity": 1
"product_id": 48911,
"variation_id": 0,
"quantity": 1,
"product_id": 45329,
"variation_id": 0,
"quantity": 1
The output that I want to achieve is this:
45329 quantity 2
48911 quantity 1
Thanks!
Decode JSON with json_decode() and make calculations. Next example uses simplified JSON data, which I think matches the format from WooCommerce (I guess this format is from list orders GET request):
<?php
# JSON
$json = '
[
{
"id": 727,
"line_items": [
{
"id": 315,
"name": "Woo Single #1",
"product_id": 93,
"variation_id": 0,
"quantity": 2,
"tax_class": "",
"subtotal": "6.00",
"subtotal_tax": "0.45",
"total": "6.00",
"total_tax": "0.45",
"taxes": [
{
"id": 75,
"total": "0.45",
"subtotal": "0.45"
}
],
"meta_data": [],
"sku": "",
"price": 3
},
{
"id": 316,
"name": "Ship Your Idea – Color: Black, Size: M Test",
"product_id": 22,
"variation_id": 23,
"quantity": 1,
"tax_class": "",
"subtotal": "12.00",
"subtotal_tax": "0.90",
"total": "12.00",
"total_tax": "0.90",
"taxes": [
{
"id": 75,
"total": "0.9",
"subtotal": "0.9"
}
],
"meta_data": [
{
"id": 2095,
"key": "pa_color",
"value": "black"
},
{
"id": 2096,
"key": "size",
"value": "M Test"
}
],
"sku": "Bar3",
"price": 12
}
]
}
]';
$input = json_decode($json, true);
# Sum
$output = array();
foreach ($input as $order) {
foreach ($order["line_items"] as $item) {
$product_id = $item['product_id'];
$quantity = $item['quantity'];
if (!array_key_exists($product_id, $output)) {
$output[$product_id] = 0;
}
$output[$product_id] += $quantity;
}
}
#Output
foreach ($output as $key => $value) {
echo $key.' quantity '.$value.'<br>';
}
?>
Output:
93 quantity 2
22 quantity 1
Good morning guys!
I'm having a hard time trying to figure out how to arrange the following JSON:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
Into this:
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology", "Bachelor in Sociology",
"Number": "53","109",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}]
}
Basically, put the same degrees in one place and have all the names of said degree separated by a comma
I already have this JSON decoded into a variable:
$data = json_decode($topDegrees[1]["diplomas"],true);
Thanks in advance for your help!
I came up with this
$json = <<<JSON
{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor's Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor's Degree"
}]
}
JSON;
$data = json_decode( $json, true );
$degrees = $data['degrees'];
$names = array_column($degrees, 'degree');
$count = array_count_values($names);
$duplicates = array_filter($count, function($var) {
return $var > 1;
});
foreach ( array_flip($duplicates) as $degree ) {
$filter = array_filter($degrees, function($var) use ($degree) {
return ( $var['degree'] === $degree );
});
$names = [];
$numers = [];
foreach ( $filter as $item ) {
$names[] = $item['Name'];
$numbers[] = $item['Number'];
}
$indices = array_keys($filter);
$index = array_shift($indices);
$degrees[$index]['Name'] = $names; // = join(', ', $names);
$degrees[$index]['Number'] = $numbers; // = join(', ', $numbers);
while ( count($indices) ) {
unset($degrees[array_shift($indices)]);
}
}
$data['degrees'] = $degrees;
print_r(json_encode($data));
// {"showElement":"1","degrees":[{"Name":["Bachelor in Psychology","Bachelor in Sociology"],"Number":["53","109"],"degree":"Bachelor's Degree"},{"Name":"Certificate","Number":"56","degree":"Certificate"},{"Name":"High School Diploma","Number":"28","degree":"High School"}]}
Your wanted json output is not valid, i have made an array structure in its place. If you want comma separated text, just use the join statements I've commented out.
$str = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelor\'s Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelor\'s Degree"
}]
}';
$str_arr = json_decode($str);
foreach($str_arr->degrees as $k=>$val){
if($val->degree == 'Bachelor\'s Degree'){
$new['Bachelor'][] = $val;
}else{
$new[] = $val;
}
}
foreach($new['Bachelor'] as $aa){
$nameStr[]= $aa->Name;
$numStr[] = $aa->Number;
}
$nameStr = implode(', ', $nameStr);
$numStr = implode(', ', $numStr);
$degree = 'Bachelor\'s Degree';
$new[] = (object) array($nameStr, $numStr, $degree);
unset($new['Bachelor']);
echo $json = json_encode($new);
echo "<pre>"; print_r(json_decode($json));
Hope this helps.
Demo here
This should do it:
<?php
$json = '{
"showElement": "1",
"degrees": [{
"Name": "Bachelor in Psychology",
"Number": "53",
"degree": "Bachelors Degree"
}, {
"Name": "Certificate",
"Number": "56",
"degree": "Certificate"
}, {
"Name": "High School Diploma",
"Number": "28",
"degree": "High School"
}, {
"Name": "Bachelor in Sociology",
"Number": "109",
"degree": "Bachelors Degree"
}]
}';
$items = json_decode($json, true);
$orderedItems = [];
$final = ['showElement' => 1];
foreach ($items['degrees'] as $item) {
$orderedItems[$item['degree']]['Name'][] = $item['Name'];
$orderedItems[$item['degree']]['Number'][] = $item['Number'];
$orderedItems[$item['degree']]['degree'] = $item['degree'];
}
foreach ($orderedItems as $order) {
$order['Name'] = (count($order['Name']) > 1) ? $order['Name'] : $order['Name'][0];
$order['Number'] = (count($order['Number']) > 1) ? $order['Number'] : $order['Number'][0];
$final['degrees'][] = [
'Name' => $order['Name'],
'Number' => $order['Number'],
'degree' => $order['degree']
];
}
echo json_encode($final);
Solution
To get total price from loop in json we need to use $tot += +$data['price'].","; in below code
$arr = '[{
"id": 1,
"name": "A green door",
"price": 11,
"tags": ["home", "green"]
},
{
"id": 2,
"name": "A green door",
"price": 15,
"tags": ["home", "green"]
},
{
"id": 3,
"name": "A green door",
"price": 10,
"tags": ["home", "green"]
}]';
//print_r($arr);
$arr = json_decode($arr,TRUE);
foreach ($arr as $data)
{
$tot += +$data['price'].",";
}
echo "Total = ".rtrim($tot,',');
Use this,
$arr = json_decode($arr,TRUE);
echo "Total = ".array_sum(array_column($arr,"price"));
array_sum - Calculate the sum of values in an array
array_column - Return the values from a single column in the input array
Give it a try, this will work.
$arr = json_decode($arr,TRUE);
foreach ($arr as $data)
{
$tot[] =$data['price'];
}
echo "Total=".array_sum($tot);
Below is json code where i have o display its values. How to fetch the output as given below
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
Output should come like this
Name : Le Grand Bouquet Blanc, Price : 65
Name : Roses, Price : 33
Name : Mandarine, Price : 125
Total: 223 Euro
Any Help?
JSON decode, loop through the data and output the required text like so:
$data = json_decode($jsondata);
$total = 0;
foreach($data->flowers as &$datum) {
printf('Name : %s, Price: %d'.PHP_EOL, $datum->name, $datum->price);
$total += $datum->price;
}
printf('Total: %d Euro'.PHP_EOL, $total);
Read up on some basic PHP functions/concepts:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.printf.php
http://php.net/manual/en/function.echo.php
http://php.net/manual/en/language.operators.arithmetic.php
Try using json_decode() with true as second attribute to convert JSON it into array first.Then use foreach loop and get desired result.
<?php
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$array = json_decode($jsondata,true);
//print_r($array);
$sum = 0;
foreach($array['flowers'] as $flowers)
{
echo "Name : ".$flowers['name'].",Price : ".$flowers['price'].PHP_EOL;
$sum+=$flowers['price'];
$currency = $flowers['currency'];
}
echo "Total:".$sum." ".$currency;
Try this.
$jsondata = '{
"flowers": [
{
"id": "1",
"name": "Le Grand Bouquet Blanc",
"price": "65",
"currency": "euro"
},
{
"id": "2",
"name": "Roses",
"price": "33",
"currency": "euro"
},
{
"id": "3",
"name": "Mandarine",
"price": "125",
"currency": "euro"
}
]
}';
$data = json_decode($jsondata,true);
echo "Name : " . $data['flowers'][0]['name'] . ' , Price: ' . $data['flowers'][0]['price'] ;