Adding Across Arrays - php

I structured the item information in an unorthodox way, it is stored in three different arrays and are related by the key. I am looking to Sum the Quantities by ItemID.
1. Array #1 ItemID
$_SESSION["item_id"][]
1 => 1, 2 => 1, 3 =>2
2. Array #2 Size
$_SESSION["size"][]
1 => S, 2 => L, 3 =>S
3. Array #3 Quantity
$_SESSION["count"][]
1 => 250, 2 =>750, 3=>250
The result should be as follows:
ItemID # 1 --> Quantity 1000
ItemID # 2 --> Quantity 250
Could someone could help me with a function ?

Let's say, you have the following array in $_SESSION:
$_SESSION['item_id'] = array(1, 1, 2);
$_SESSION['size'] = array('S', 'L', 'S');
$_SESSION['count'] = array(250, 750, 250);
NOTE: the following answer take assumption that array length in those 3 SESSION value are equal.
You will need to create new array to store the result:
$newArrayResult = array();
After that, you will need to do for...each loop to extract currently accessed key:
foreach($_SESSION['item_id'] as $key => $value){
//the logic goes here
}
Next, we will use item_id as our array key in $newArrayResult. To do that, we will need to check first, if it is already defined. If not, create the key with default value 0. We do the checking by using built in function called array_key_exists. This way, we will avoid running into undefined key index error.
if(!array_key_exists($value, $newArrayResult)){
$newArrayResult[$value] = 0;
}
After we have the key for $newArrayResult, next step would be to simply store count value into it:
$newArrayResult[$value] += $_SESSION['count'][$key];
Done. Print the result to test:
print_r($newArrayResult);
Here is the whole code again, for you to copy-paste. Don't forget to read and understand the above flow first:
$_SESSION['item_id'] = array(1, 1, 2);
$_SESSION['size'] = array('S', 'L', 'S');
$_SESSION['count'] = array(250, 750, 250);
$newArrayResult = array();
foreach($_SESSION['item_id'] as $key => $value){
if(!array_key_exists($value, $newArrayResult)){
$newArrayResult[$value] = 0;
}
$newArrayResult[$value] += $_SESSION['count'][$key];
}
print_r($newArrayResult);

Related

Sorting simple Object [duplicate]

This question already has answers here:
Sort a flat, associative array by numeric values, then by non-numeric keys
(8 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Base material :
I have a base list $food :
[{"id":"123","name":"apple"},{"id":"456","name":"Rost Beef"},...]
that i first reduce with $food_reduced = array_count_values(array_columns($food, "id"));.
[{123:2},{456:5},...]
Then i loop through $food_reduced with foreach($food_reduced as $id => $count) to query a DataBase to get the category (vegetables, fruits, meat, fish, etc..) that i store into $food_byCategory = array(); declared right before the loop :
if ($food_byCategory[$row["ctg_name"]])
{
$food_byCategory[$row["ctg_name"]] += $count;
}
else
{
$food_byCategory[$row["ctg_name"]] = $count;
}
Which gives me this array that I want to sort (gettype() says it's an Array at least) in PHP :
{
Vegetable: 2
Fruit: 1
Fish: 5
Drinks: 1
Meat: 2
Desert: 3
}
to this :
{
Fish: 5
Desert: 3
Meat: 2
Vegetable: 2
Drinks: 1
Fruit: 1
}
Notice the sorting by key once the sorting by value is done.
The goal is then to display this list into an html list by value descending.
I have tried asort, sort, arsort, with or without the option SORT_NUMERIC etc...
Wether it's not working at all or it's erasing the keys and replacing them with indexes.
I've also tried typecasting it into an array, but nothing changed (probably because it is an Array already ? But yet, not an Object ?)
I'm kinda lost.
Help ?
SOLVED my issue by building the "count" array another way :
if (!in_array($ctg_id, array_column($food_byCategory, "id")))
{
$food_byCategory[] = array(
"id" => $ctg_id,
"count" => 1
);
}
else
{
$index = array_search($ctg_id, array_column($food_byCategory, "id"));
$food_byCategory[$index]["count"]++;
}
and then sorting it with usort :
usort($food_byCategory, function($a, $b) {
return $b["count"] <=> $a["count"];
});
asort() applies to associative arrays, not objects.
You can easily transform your object into a associative array by typecasting it as describe here.
$array = (array) $yourObject;
You can use a php function called sort, try something like this:
$myArray = array(4, 6, 2, 22, 11);
sort($myArray);
result: 2, 4, 6, 11, 22
or
$myArray = array(4, 6, 2, 22, 11);
rsort($myArray);
result: 22, 11, 6, 4, 2

Get the biggest value from array

I have this array where i need to get the biggest value but the biggest key
Array = [
0 = 2,
1 = 2,
2 = 1,
3 = 1,
],
the biggest value from array above are 2, but there's 2 keys where it has values of 2 which is 0 and 1. somehow i need to get the key of array where it's biggest one so the key are 1. and i just can't reorder the value since it'll mess up the key value because i'm gonna need the key
All you need is a loop that progresses through the array, along with two variables that you update appropriately as needed:
maxValue: The largest value seen so far
maxKey: The key for the largest value seen so far
During the loop, check the current element's key and value against these. If the value matches maxValue but the key is greater, update maxKey. If the value is greater than maxValue, change BOTH maxKey and maxValue to match the current element's key and value.
One approach would be to first filter the associative array, retaining only entries whose values are coincident with the highest value. Then, take the max value of array_keys() of that subarray to find the highest key.
$array = Array
(
0 => 2,
1 => 2,
2 => 1,
3 => 1
);
$array_max = array_filter($array, function($elem) USE ($array) {
return $elem == max($array);
});
echo max(array_keys($array_max));
hope this help you , first will get highest value with max($array) then will get max key
$array = array('2','2','1','1');
$highest_num = max($array);
$highest_key = max(array_keys($array,$highest_num));
print_r($highest_key);

Find values in PHP Array and calculate

I am trying to make a function where I get data from specific positions in an array, and then add(plus) the results together. Something like this:
$specificPositionsInArray = "1,4,12,27,40,42,48,49,52,53,56,58";
$dataArray = "1,2,3,4,5,6,7,8"; // More than hundred values.
myfunction($specificPositionsInArray) {
// Find position in array, based on $specificPositionsInArray and then
// plus the value with the previous value
// that is found in the $specificPositionsInArray.
// Something like:
$value = $value + $newValue;
return $value;
}
So if $specificPositionsInArray was 1,3,5
The $value that should be returned would be: 9 (1+3+5) (based on the $dataArray).
Maybe there is another way to do it, like without the function.
Here's a functional approach:
$specificPositionsInArray = array(1,3,7,6);
$dataArray = array(1,2,3,4,5,6,7,8);
function totalFromArrays($specificPositionsInArray, $dataArray) {
foreach ($specificPositionsInArray as $s){
$total += $dataArray[$s];
}
return $total;
}
$total = totalFromArrays($specificPositionsInArray, $dataArray);
echo $total;
You should look into arrays and how to handle them, you could have found the solution pretty easily. http://www.php.net/manual/en/book.array.php
//$specificPositionsInArray = array(1,4,12,27,40,42,48,49,52,53,56,58);
$specificPositionsInArray = array(1,3,5);
$dataArray = array(1,2,3,4,5,6,7,8);
$total=0;
foreach($specificPositionsInArray as $k => $v){
$total += $dataArray[$v-1];
}
echo $total;
The weird part about this is the $v-1 but because of how you want to handle the addition of the items, and an array starts with element 0, you have to subtract 1 to get to the right value.
So you want to do something like this:
$dataArray = array(1,2,3,4,5...); // 100+ values, not necessarily all integers or in ascending order
$specificPositions = array(1, 3, 5);
function addSpecificPositions($data, $positions) {
$sum = 0;
foreach($positions as $p)
$sum += $data[$p];
return $sum;
}
If you really want to keep your list of values in a string (like you have it in your example), you'll have to do an explode first to get them in array form.
Since it looks like your array is using numeric values for the keys this should be fairly easy to calculate. I refactored your code a little to make it easier to read:
$specificPositionsInArray = array(1,4,6,7);
By default PHP will assign numeric keys to each value in your array, so it will look like this to the interpreter.
array(
[0] => 1,
[1] => 4,
[2] => 6,
[3] => 7
)
This is the same for all arrays unless you specify a numeric or mixed key. Since the data array seems to just be values, too, and no keys are specified, you can simply target them with the key that they will be associated with. Say I use your array example:
$dataArray = array(1,2,3,4,5,6,7,8);
This will look like this to the parser:
array(
[0] => 1,
[1] => 2,
[2] => 3,
[3] => 4,
[4] => 5,
[5] => 6,
[6] => 7,
[7] => 8
)
If you wanted to select the number 6 from this array, you actually need to use $dataArray[5] since array keys start at zero. So for your function you would do this:
$specificPositionsInArray = array(1,4,6,7);
$dataArray = array(1,2,3,4,5,6,7,8);
calculate_array($specificPositionsInArray, $dataArray); // Returns 18
function calculate_array($keys, $data){
$final_value = 0; // Set final value to 0 to start
// Loop through values
foreach($keys as $key){
// Add the keys to our starting value
$final_value += $data[$key-1]; // minus 1 from key so that key position is human readable
}
// return the sum of the values
return $final_value;
}

Remove element and reindex

the logic is to get last element from the elemnt after particular interval when all the elemnts are been removed. suppose there are five users and every secound user is been eliminated , then i have to find the last remaining user.
$foo = array(
'0'=>'1',
'1'=>'2',
'2'=>'3',
'3'=>'4',
'4'=>'5',
'5'=>'6'
);
now remove element indexed at 2 and reindex the array in below format.
$foo = array(
'0'=>'4',
'1'=>'5',
'2'=>'6',
'3'=>'1',
'4'=>'2',
);
You can use unset(), but you'll also need to call array_values() to force a re-index. For example:
unset($foo[2]);
$foo = array_values($foo);
The original question is a bit unclear. I understand you want to remove index X, and place all items after index X as first items in the array.
$index2remove = 2;
$newArray1 = array_slice($foo, $index2remove+1); // Get items after the selected index
$newArray2 = array_slice($foo, 0, $index2remove); // get everything before the selected index
$newArray = array_merge($newArray1, $newArray2); // and combine them
Or shorter and a bit less memory consuming (but harder to read):
$index2remove = 2;
$newArray = array_merge(
array_slice($foo, $index2remove+1), // add last items first
array_slice($foo, 0, $index2remove) // add first items last
);
You do NOT need to unset value 2 in my code, you simple slice it out. We do that with the -1 in the 2nd splice function.
If you want, you can replace $newArray = array_merge() with $foo = array_merge(), but ONLY in the second, if you dont need to save the original array.
Edit: Changed small error, thank you plain jane
Try this of which the output is given below
$foo = array('0'=>'1','1'=>'2','2'=>'3','3'=>'4','4'=>'5','5'=>'6');
//need to input this as the index of the element to be removed
$remove_index = "2";
unset($foo[$remove_index]);
$slice1 = array_slice($foo, 0, $remove_index);
$slice2 = array_slice($foo, $remove_index);
$final_output = array_merge($slice2, $slice1);
Output
Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 1
[4] => 2
)

php arrays get the order number of a certain element

Lets say i have an array in PHP
$test['michael_unique_id'] = 3;
$test['john_unique_id'] = 8;
$test['mary_unique_id'] = 10;
.
.
.
.
$test['jimmy_unique_id'] = 4;
(the values (3,8,10.........4) are unique)
Lets say i want to search for the unique id 10, and get the order of the matching element in the array. In this example, the third element has the value 10, so i should get the number 3.
I can do it by scanning with a for loop looking for the value i'm searching and then get the $i value when i have a match, but i wonder if there is any built-in function (or a better method) that implements this.
You can get all of the array's values as an array with array_values() and then use array_search() to get the position (offset) of that value in the array.
$uniq_id = 10;
$all_vals = array_values($test); // => array(3, 8, 10, ... )
echo array_search( $uniq_id, $all_vals ); // => 2
Because PHP array indices are zero-based, you'll get 0 for the first item, 1 for the second item, etc. If you want the first item to be "1," then just add one. All together now:
$uniq_id = 10;
echo array_search( $uniq_id, array_values( $test ) ) + 1; // => 3
It's not clear to me, however, that this is necessarily as performant as just doing a foreach:
$uniq_id = 10;
$idx = 1;
foreach($test as $val) {
if($val == $uniq_id) {
break;
}
$idx++;
}
echo $idx; // => 3
Well, array_search will give you the key, but in your case, you want the index of that key, so I believe a loop is your best bet. Is there a good reason why you need the index? It doesn't seem very useful to me.

Categories