PHP sum up value in foreach separate - php

Hi I am new to php and I faced some problem when I need sum up array in foreach.
I had array like this:
$arrays = [
[
'orderid' => "1",
'price' => "100"
'rate' => "1"
],
[
'orderid' => "2",
'price' => "200"
'rate' => "5"
],
];
What I face when I using foreach, the price * rate will sum continuously but not sum up separately.
$bonus = array();
foreach($arrays as $data){
$bonus = $data['originalPrice'] * $data['rate'];
}
I also tried using array_map() but also cannot get my answer;
WHat I need about :
$array = [
[
'total' => 100;
],
[
'total' => 1000;
]
]
Any idea for help?
UPDATED: ALL THE ANSWER ARE CORRECTED, is the api data give me wrong info lol.

foreach($arrays as $data){
$bonus[]['total'] = $data['price'] * $data['rate'];
}
print_r($bonus);

You are using price so use that property and you need to push the value in the result array. Thus, you need to do:
<?php
$arrays=array(
array(
'orderid' => "1",
'price' => "100",
'rate' => "1"
),
array(
'orderid' => "2",
'price' => "200",
'rate' => "5"
)
);
$bonus = array();
foreach($arrays as $data){
array_push($bonus,$data['price'] * $data['rate']);
}
print_r($bonus);
?>
You can test this code at http://www.writephponline.com/

Foreach is fine, but you need to add to the bonus array rather than override with the result:
$bonus = array();
foreach($arrays as $data){
$bonus[] = array('total' => $data['originalPrice'] * $data['rate']);
}
This is adding arrays to the bonus array.

Related

convert array to group keys and group values in PHP

Hello I have an array and want to group keys and values as shown below:
[
"agre" => "0"
"extr" => "0"
"inte" => "100"
]
I want to convert it to
{"labels":["agre","extr","inte"],"points":[0,0,100]}
Just create a new array of the keys and the values.
$data = [
"agre" => "0",
"extr" => "0",
"inte" => "100",
];
echo json_encode([
'labels' => array_keys($data),
'points' => array_map('intval', array_values($data))
]);
prints
{"labels":["agre","extr","inte"],"points":[0,0,100]}
Try this code.
<?php
$data = array(
"agre" => "0",
"extr" => "0",
"inte" => "100"
);
$newData = array('labels' => array(), 'points' => array());
foreach($data as $key => $value) {
$newData['labels'][] = $key;
$newData['points'][] = $value;
}
print_r($newData);
?>
Isn't this what you wanted?

How do I do multiplication in a php multi dimention array

how can i show php array multiplying in loop
I have to show in the foreach so that I can add mysql
$data = [
[
"id" => "3202",
"total" => "5"
],[
"id" => "3190",
"total" => "2"
],[
"id" => "3199",
"total" => "5"
]
];
foreach($data as $v){
//$v["total"]*
//output = 5x2x5= 50
}
You can use array_column and array_product in this problem:
<?php
$data = [
['id' => '3202','total' => '5'],
['id' => '3190','total' => '2'],
['id' => '3199','total' => '5']
];
$total = array_column($data, 'total');
$product = array_product($total);
printf('The product of total: %s', $product);
PHP array functions online
<?php
$data = [
['id' => '3202','total' => '5'],
['id' => '3190','total' => '2'],
['id' => '3199','total' => '5']
];
$total = 1; // empty product
$output = [];
foreach($data as $v) {
$total *= $v['total'];
$output[] = $v['total'];
}
echo implode('x', $output) . '= ' . $total; // 5x2x5= 50
Might want to also add logic to check if the $data is empty first with count($data), then when the list is empty, output a message instead.

Update array with post values

im currently trying to update an array with values from another one.
Basically there is a form where you can update data for an object, the form sends a json array like so:
{
"name": "Test2",
"address": "Adresas 2",
"object_id": "44",
"job_id": [
"31",
"33"
],
"amount": [
"500",
"500"
]
}
My goal is to update another array that is being fetched from the database with values of job_idd and amount.
The array from database looks like so:
{
"jobs": [
{
"id": "31",
"amount": "500",
"have": 250
},
{
"id": "33",
"amount": "500",
"have": 0
}
]
}
I need to update the second array values "amount" with the posted values from the first array "amount", but so that the second array still has the original "have" values
I tried using nested foreach method:
$object_id = $_POST['object_id'];
$data = json_encode($_POST);
$json = json_decode($data, true);
$i = 0;
foreach($json['job_id'] as $item) {
$job_id = $item;
$query33 = "SELECT * FROM `objektai` WHERE id='$object_id'";
$result33 = mysqli_query($conn, $query33) or die(mysqli_error($conn));
while($row2 = mysqli_fetch_array($result33)){
$job_info = $row2['info'];
}
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $key2 => $entry2) {
$have = $json_22['jobs'][$key2]['have'];
}
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $have,
);
$i++;
}
Usinng the example above the foreach prints the values 2 times and my updated json "have"
has a value of 0, the "amount" entries are updated correctly
Thanks in advance for you help!
UPDATE
adding var_export($_POST):
array ( 'name' => 'Test2',
'address' => 'Adresas 2',
'object_id' => '44',
'job_idd' => array (
0 => '31',
1 => '33',
),
'darbo_kiekis' => array (
0 => '500',
1 => '500',
),
)
When you're looping through the array from the database, you need to compare the id value with $obj_id.
I've also shown below how to use a prepared statement to prevent SQL injection.
I've removed lots of unnecessary code:
No need to convert $_POST to/from JSON.
Use $i => in the foreach loop to get the array index.
You don't need a while loop when processing the query results if it only returns one row.
You don't need $key2, you can just use $entry2.
$object_id = $_POST['object_id'];
$query33 = "SELECT * FROM `objektai` WHERE id = ?";
$stmt33 = $conn->prepare($query33);
$stmt33->bind_param('i', $job_id);
foreach($_POST['job_id'] as $i => $job_id) {
$stmt33->execute();
$result33 = $stmt33->get_result();
$row2 = $result33->fetch_assoc();
$job_info = $row2['info'];
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $entry2) {
if ($entry2['id'] == $job_id) {
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $entry2['have']
);
}
}
}

Add grouping elements to 2d array and sum values in respective group

I need to add new elemets to my array when a new category value is encountered. When a category value is encountered after the first time, its value1 and value2 values should be added to the first encounter's respective values.
Also, in the result array, I no longer wish to keep the category column. The category-grouping rows should use the category value as its name value.
Sample input:
$datas = [
[
'category' => 'Solution',
'name' => 'Name1',
'value1' => 20,
'value2' => 21
],
[
'category' => 'Solution',
'name' => 'Name2',
'value1' => 30,
'value2' => 31
],
[
'category' => 'Solution1',
'name' => 'Name3',
'value1' => 40,
'value2' => 41
]
];
Desired result:
[
['name' => 'Solution', 'value1' => 50, 'value2' => 52],
['name' => 'Name1', 'value1' => 20, 'value2' => 21],
['name' => 'Name2', 'value1' => 30, 'value2' => 31],
['name' => 'Solution1', 'value1' => 40, 'value2' => 41],
['name' => 'Name3', 'value1' => 40, 'value2' => 41]
]
I tried like this:
private function groupByProductSuperCategory($datas)
{
$return = [];
foreach ($datas as $data) {
$return[$data['category']][$data['name']] = array_sum(array_column('category', $data);
}
return $return;
}
The idea is to calculate first all sum values for by category, and after that just put values from name like another array. Have you an idea of how to do that?
From the posted array... To end in the desired array, there is some tiny fixes to do first. But I assumed it was due to typos while copying here...
So here is the array I started with:
$result = [
0 => [
"category" => 'Solution',
"name" => 'Name1',
"value1" => 20,
"value2" => 21
],
1 => [
"category" => 'Solution',
"name" => 'Name2',
"value1" => 30,
"value2" => 31
],
2 => [
"category" => 'Solution1',
"name" => 'Name3',
"value1" => 40,
"value2" => 41
]
];
Now, that re-organization of the data is a bit more complex than it looks... You need to perform several loops to:
Find distinct "category" names
Perform the summations for each
Add the sum item and the single items
So here is the code I ended with:
function groupByProductSuperCategory($datas){
$category = [];
$return = [];
// Find distinct categories
foreach ($datas as $data) {
if(!in_array($data["category"],$category)){
array_push($category,$data["category"]);
}
}
// For each distinct category, add the sum item and the single items
foreach ($category as $cat) {
// Get the sums
if(!in_array($cat,$return)){
$sum1 = 0;
$sum2 = 0;
foreach ($datas as $data) {
if($data["category"] == $cat){
$sum1 += $data["value1"];
$sum2 += $data["value2"];
}
}
}
// Push the sums in the return array
array_push($return,[
"name" => $cat,
"value1" => $sum1,
"value2" => $sum2,
]);
// Push the single elements
foreach ($datas as $data) {
if($cat == $data["category"]){
array_push($return,[
"name" => $data["name"],
"value1" => $data["value1"],
"value2" => $data["value2"],
]);
}
}
}
return $return;
}
Here is a PHPFiddle to try it out... Hit [F9] to run.
It is much more direct, efficient, and readable to implement a single loop and push reference variables into the result array to allow summing based on shared categories without keeping track of the actual indexes of the category rows.
Code: (Demo)
$result = [];
foreach ($array as $row) {
if (!isset($ref[$row['category']])) {
$ref[$row['category']] = [
'name' => $row['category'],
'value1' => 0,
'value2' => 0
];
$result[] = &$ref[$row['category']];
}
$ref[$row['category']]['value1'] += $row['value1'];
$ref[$row['category']]['value2'] += $row['value2'];
unset($row['category']);
$result[] = $row;
}
var_export($result);

php - How to insert a foreach loop inside a multidimensional array

How to insert a foreach loop inside a multidimensional array ?
I have a multidimensional array that I use to connect my website to Mailchimp. I have to check with a foreach loop the number of products that the user buys, and add these insiede a array call "lines".
This is at moment my json code, that after I will send to Mailchimp:
$json_data = '{
"id": "2'. $order->id .'",
"customer": {
"id": "71",
"email_address": "'.$order->email.'",
"opt_in_status": true,
"company": "'.$order->company_name.'",
"first_name": "'.$order->pad_firstname.'",
"last_name": "'.$order->pad_lastname.'",
"orders_count": 1,
"total_spent": 86
},
"checkout_url": "https://www.mywebsite.it/en/checkout/confirmation/",
"currency_code": "EUR",
"order_total": 86,
"lines"[{
'.$line_result.'
}]
}';
The $line_result is where I try to add the array of the products.
I know is wrong.
all the array inside the "lines" need be like this:
"lines":[
{
data product 1 ...
},
{
data product 2 ...
}
]
This is my foreach:
foreach ($order->pad_products as $product) {
$line_result['line'] = array(
"id" => "$order->id",
"product_id" => "$product->pad_product_id",
"product_title" => "$product->title",
"product_variant_id" => "$product->id",
"product_variant_title" => "$product->title",
"quantity" => "$product->pad_quantity",
"price" => "$product->prezzo",
);
};
what is the correct way to insert this data and create a multidimensional array like the one I need?
Thank you.
You just need to store all $line_result in global variable, and then, bind it to your json model :
$results = [];
foreach ($order->pad_products as $product) {
$results[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
};
$data = json_decode($json_data, true);
$data['lines'] = $results;
$json = json_encode($data);
EDIT : Script array to json
$lines = [];
foreach ($order->pad_products as $product) {
$lines[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
}
$data = [
'id' => '2'.$order->id,
'customer' => [
'id' => '71',
'email_address' => $order->email,
'opt_in_status' => true,
'company' => $order->company_name,
'first_name' => $order->pad_firstname,
'last_name' => $order->pad_lastname,
'orders_count' => 1,
'total_spent' => 86
],
'checkout_url' => 'https://www.mywebsite.it/en/checkout/confirmation',
'currency_code' => 'EUR',
'order_total' => 86,
'lines' => $lines
];
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
I want say thank you to #adrianRosi for the help and the input he gives me.
In the end I find my solution, that it's json_encode the array before add into $data in json format.
in this way:
$product_list = [];
foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};
$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}
$prezzo_totale = $order->pad_price_total;
$json_data = '{
...
...
'.$json_products_edit.'
}';

Categories