Find sum of all keys in Session array - php

I am using a form to create several arrays in a Session. Each time the form is submitted a new _SESSION['item'][] is made containing a new array. The code for this:
$newitem = array (
'id' => $row_getshoppingcart['id'] ,
'icon' => $row_getimages['icon'],
'title' => $row_getimages['title'],
'medium' => $row_getshoppingcart['medium'],
'size' => $row_getshoppingcart['size'],
'price' => $row_getshoppingcart['price'],
'shipping' => $row_getshoppingcart['shipping']);
$_SESSION['item'][] = $newitem;
There could be any number of item arrays based on how many times the user submits the form. How can I get the total of the key 'price' from every item in the entire session and echo it on the page?
Thank you in advance for your time. I really appreciate it.

Try this (untested):
$sum = 0;
foreach ($_SESSION['item'] as $item)
$sum += $item['price'];
echo $sum;

Loop through them:
$total = 0;
foreach($_SESSION['item'] as $item) {
$total += $item['price'];
}
echo $total;

Related

Create Array Inside Foreach Loop

How to put these codes in a foreach loop?
$item1_details = array(
'id' => 'a1',
'price' => 18000,
'quantity' => 3,
'name' => "Apple"
);
$item2_details = array(
'id' => 'a2',
'price' => 20000,
'quantity' => 2,
'name' => "Orange"
);
Then the array above will be saved in a variable. It's an array. And, yes, I have no idea how to do a loop inside array. So please help me for this too.
$item_details = array ($item1_details, $item2_details);
Thus, I have to questions. First, how to create an array inside a foreach loop. Second, How to loop inside an array.
You don't put a loop inside an array, you push onto the array in a loop.
$item_details = array();
for ($i = 0; $i < 10; $i++) {
$item_details[] = $item1_details;
$item_details[] = $item2_details;
}
This will make an array with 10 alternating copies of $item1_details and $item2_details.
You mentioned a foreach loop, but that's for looping over an array that already exists. You didn't show any array to loop over, so I'm not sure how it applies in this case.
You can use array_values with array_merge
$f = array_merge(array_values($item1_details), array_values($item2_details));
Working example :- https://3v4l.org/fDM3N

how do i loop through an associative array with multiple values

I just started learning php and I have this issue. I'm trying to loop through this array to get the total value of each key and output the student with the highest number. I'd really appreciate your inputs
$students = array(
'Mary' => [20,45,12],
'Grace' => [40,78,56],
'John' => [61,37,58]
);
The expected output should be Grace but i can't seem to get it to work.
You don't have to loop. Just calculate all the totals
$totals = array_map('array_sum', $students);
then output the key of the array with the maximum total.
echo array_keys($totals, max($totals))[0];
Something like this maybe assuming all grades will be positive
$students = array(
'Mary' => [20,45,12],
'Grace' => [40,78,56],
'John' => [61,37,58]
);
$highest_grade = 0;
$higest_person = "";
foreach($students as $key => $value) {
$max = max($value);
if ($highest_grade <= $max) {
$highest_grade = $max;
$highest_person = $key;
}
}
echo $highest_person . '->' . $highest_grade;
Output is using http://phptester.net/
Grace->78

PHP calculate array data

I am having trouble to calculate the sum of an array values
my array is
$bar_chart_data =
array(
array(
array("Data1",548.25),
array("Data2",238.75),
array("Data3",95.50),
array("Data4",300.50),
array("Data5",286.80),
array("Data6",148.25)
)
);
I am using this php code to calculate the results but its always gives me 0
$sumArray = array();
foreach ($bar_chart_data as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$sumArray[$id]+=$value;
}
}
print_r($sumArray);
Your $id is different in all iteration.
You have to use $sumArray[$k]+=$value[1];.
You also have to init $sumArray[$k] to 0 between your two foreach.
I believe you have an array containing a sub-array and you want to get the sum of all the values in each of the sub-arrays.
I suggest you use an associative sub-array to make the task easier.
$bar_chart_data = array(
array(
"Data1" => 548.25,
"Data2" => 238.75,
"Data3" => 95.50,
"Data4" => 300.50,
"Data5" => 286.80,
"Data6" => 148.25
),
array(
)
);
$sumArray = array(); // Create an empty array to store the sum of each sub-array
foreach ($bar_chart_data as $subArray) {
$sum = 0; // Initialize sum as zero
foreach ($subArray as $key=>$value) {
$sum += $value;
}
$sumArray[] = $sum; // Append each sum to the array
}
print_r($sumArray); // Print the array containing the sums.
You only need one loop, then extract the values at index 1 and sum them:
foreach($bar_chart_data as $values) {
$sumArray[] = array_sum(array_column($values, 1));
}
You can add the $k => $values back and use $sumArray[$k] if needed, but the way your array is shown it will work without it.

Exploding and replacing one array field

So, I have an array that, for unrelated reasons, has one imploded field in itself. Now, I'm interested in exploding the string in that field, and replacing that field with the results of the blast. I kinda-sorta have a working solution here, but it looks clunky, and I'm interested in something more efficient. Or at least aesthetically pleasing.
Example array:
$items = array(
'name' => 'shirt',
'kind' => 'blue|long|L',
'price' => 10,
'amount' => 5);
And the goal is to replace the 'kind' field with 'color', 'lenght', 'size' fields.
So far I've got:
$attribs = array('color', 'lenght', 'size'); // future indices
$temp = explode("|", $items['kind']); // exploding the field
foreach ($items as $key => $value) { // iterating through old array
if ($key == 'kind') {
foreach ($temp as $k => $v) { // iterating through exploded array
$new_items[$attribs[$k]] = $v; // assigning new array, exploded values
}
}
else $new_items[$key] = $value; // assigning new array, untouched values
}
This should (I'm writing by heart, don't have the access to my own code, and I can't verify the one I just wrote... so if there's any errors, I apologize) result in a new array, that looks something like this:
$new_items = array(
'name' => 'shirt',
'color' => 'blue',
'lenght' => 'long',
'size' => 'L',
'price' => 10,
'amount' => 5);
I could, for instance, just append those values to the $items array and unset($items['kind']), but that would throw the order out of whack, and I kinda need it for subsequent foreach loops.
So, is there an easier way to do it?
EDIT:
(Reply to Visage and Ignacio - since reply messes the code up)
If I call one in a foreach loop, it calls them in a specific order. If I just append, I mess with the order I need for a table display. I'd have to complicate the display code, which relies on a set way I get the initial data.
Currently, I display data with (or equivalent):
foreach($new_items as $v) echo "<td>$v</td>\n";
If I just append, I'd have to do something like:
echo "<td>$new_items['name']</td>\n";
foreach ($attribs as $v) echo "<td>$new_items[$v]</td>\n";
echo "<td>$new_items['price']</td>\n";
echo "<td>$new_items['amount']</td>\n";
Associative arrays generally should not depend on order. I would consider modifying the later code to just index the array directly and forgo the loop.
Try this:
$items = array( 'name' => 'shirt', 'kind' => 'blue|long|L', 'price' => 10, 'amount' => 5);
list($items['color'], $items['lenght'], $items['size'])=explode("|",$items['kind']);
unset $items['kind'];
I've not tested it but it should work.
Associative arrays do not have an order, so you can just unset the keys you no longer want and then simply assign the new values to new keys.
one way
$items = array(
'name' => 'shirt',
'kind' => 'blue|long|L',
'price' => 10,
'amount' => 5);
$attribs = array('color', 'lenght', 'size');
$temp = explode("|", $items['kind']);
$s = array_combine($attribs,$temp);
unset($items["kind"]);
print_r( array_merge( $items, $s) );
This should retain the ordering because it splits the keys and values into two numerically ordered arrays and combines them at the end. It isn't more efficient, but the code is easier to read.
$kind_keys = array('color', 'length', 'size');
$kind_values = explode("|", $items['kind']);
$keys = array_keys($items);
$values = array_values($items);
$index = array_search('kind', $keys);
// Put the new keys/values in:
array_splice($keys, $index, 1, $kind_keys);
array_splice($values, $index, 1, $kind_values);
// combine the result into a new array:
$result = array_combine($keys, $values));

Setting value in Nested Php Array

Hi I'm trying to loop through a array and set a keys value. Very basic question.
The Code I tried is below.
http://pastebin.com/d3ddab156
<?php
$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));
foreach($testArray as $item)
{
$item['setTest'] = 'bob';
}
print_r($testArray);
I imagine I'm missing something stupid here and it is going to be a D'oh! moment for me. What is wrong with it?
Thanks.
You do:
$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));
foreach($testArray as $item)
{
$item['setTest'] = 'bob';
}
print_r($testArray);
$item is a copy. You change the copy, not the real array. Try this:
$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));
foreach($testArray as $key => $item)
{
$testArray[$key]['setTest'] = 'bob';
}
print_r($testArray);
Or, if you have a lot of data in the array and want to avoid creating a complete copy of each element over every iteration, simply iterate over each element as a reference. Then only a reference to that item is created i memory and you can directly manipulate the array element by using $item:
$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));
foreach($testArray as &$item)
{
$item['setTest'] = 'bob';
}
print_r($testArray);
NOTE: be sure to unset $item after the loop so you don't inadvertantly modify the array later by using that variable name.

Categories