PHP Average Values in Multiple Arrays to 1 Array - php

I have an array full of numbers and I can easily get the average of one array with.
if(count($averageprice)) {
$averageprice= array_filter($averageprice);
$averageprice= array_sum($averageprice)/count($averageprice);
}
But say I have 4 arrays all with prices. They are all in the right order and contain the same amount of values. How can I create a single array that keeps the order of each value but averages it between all arrays?
Thanks!
Edit for better example:
$array1 =array(10,15,20);
$array2 =array(14,13,22);
$array3 =array(12,18,26);
I want a new array that averages all the values in the array into one array. Note the amount of arrays isn't always the same per each time. However no matter how many arrays it is, they will always have the same amount of values in it. (Sometimes 4, sometimes 8, etc)

FIRST WAY: arrays in different variables
$arr0 = [0,10,2];
$arr1 = [0,20,4];
$arr2 = [0,30,6];
Note: array_filter will remove the 0's... For example: the average
of [0, 10, 2] will be 6 (i.e.: (10 + 2) / 2) and NOT (0+10+2)/3 = 4. Is
this really what you mean? Do you want to discard 0's before averaging?
$arr0 = array_filter($arr0);
$arr1 = array_filter($arr1);
$arr2 = array_filter($arr2);
print_r($arr0); // (just to point out again the previous comment)
Array
(
[1] => 10
[2] => 2
)
THIS IS THE IMPORTANT LINE:
$averages = array_map(function($a){return array_sum($a)/count($a);}, [$arr0, $arr1, $arr2]);
print_r($averages)
Array
(
[0] => 6
[1] => 12
[2] => 18
)
SECOND WAY: All the arrays inside a bigger array.
$arrs = [[0,10,2], [0,20,4], [0,30,6]];
$arrs = array_map(function($a){return array_filter($a);}, $arrs);
$result = array_map(function($a){return array_sum($a) / count($a);}, $arrs);
print_r($arrs);
Array
(
[0] => Array
(
[1] => 10
[2] => 2
)
[1] => Array
(
[1] => 20
[2] => 4
)
[2] => Array
(
[1] => 30
[2] => 6
)
)
print_r($result);
Array
(
[0] => 6
[1] => 12
[2] => 18
)

Related

What is the way to mearge two arrays even duplicate values exists?

sele_itmid =
Array
(
[0] => 1
[1] => 1
[2] => 5
[3] => 6
)
$recp_qty =
Array
(
[0] => 4
[1] => 16
[2] => 1
[3] => 10
)
//when i tried using
$comine = array_combine($sele_itmid,$recp_qty);
print_r($comine);exit();
am getting a result like
Array
(
[1] => 16
[5] => 1
[6] => 10
)
what i actually want is
[1]=>4
[1] => 16
[5] => 1
[6] => 10
If possible some one Please explain why array_combine neglecting it!!
after getting an array what i actually want need to sum values of same keys
"why array_combine neglecting it?" - an array doesn't allow duplicate keys.
Here is a simple solution using array_map function (it will sum up the values of the same keys):
$result = [];
array_map(function($key, $b) use (&$result){
(isset($result[$key]))? $result[$key] += $b : $result[$key] = $b;
}, $sele_itmid, $recp_qty);
print_r($result);
The output:
Array
(
[1] => 20
[5] => 1
[6] => 10
)
Sounds as though you'd want to just map the two arrays together:
function sum($v1, $v2) {
return $v1 + $v2;
}
$result = array_map('sum', $sele_itmid, $recp_qty);
In here $sele_itmid 's values are used as the key of $comine array. Since an array can not have duplicate keys first value is rejected.

Sort array based on value ascending or descending php

my array is
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)
start value is = 3
Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
[4] => 0
[5] => 1
[6] => 2
)
any idea friends..
try
$arr = array(0,1,2,3,4,5,6);
foreach($arr as $k=>$v) {
if($v >= 3)
$a[] = $v;
else
$b[] = $v;
}
$c = array_merge($a, $b);
print_r($c); //Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 6 [4] => 0 [5] => 1 [6] => 2 )
Step 0 (optional if needed):
order the array (heap or some other sort algorithm)
Step 1:
create an output array
Step 2:
loop trough the array and find your start point move the value and the ones after to new array and set the value in the original array to null
Step 3:
loop trough the array and move the remaining values over
DONE
Just do this:
Call asort on the array.
Call array_search to find the index you want to slice.
Call array_slice to cut off the part you want.
Call array_merge to merge them in the right order.
I don't know PHP that well but a quick look at php.net and I suspect this will work.
Seeing how your array is already sorted and 0-indexed, you can just slice and reorganise it:
array_values(array_slice($arr, 3, null, true) + array_slice($arr, 0, 3, true));

Change Array Keys and sort them via PHP

I looked at different options how to sort arrays. But somehow none of the given PHP commands suit my purpose.
Example - I have an array like this :
Array
(
[abc] => Array
(
[2] => 2
[3] => 3
[5] => 5
)
)
But I want to change the array to
[0] => 2
[1] => 3
[2] => 5
In other words I want to remove all keys - sort all values from LOW to HIGH and then just give em the keys from zero to X
It's much easier to work with such an array if you want to use some loops like (for, while, etc.)
Just use sort and array_values.
<?php
$array = array(
'abc' => array(
2 => 2,
5 => 5,
3 => 3,
),
);
sort($array['abc']);
$array = array_values($array['abc']);
print_r($array);
I've popped up an example at http://3v4l.org/51naW

Identify which key to modify

I'm using a SESSION variable to hold items added to an ingredients page. I'm wondering how I can uniquely identify each key in the array.
I'm adding ingredients via the following and it's working fine.
$_SESSION['ingredients'][] = array($_POST['ingredient'],$_POST['qty']);
If I stick a few ingredients in there and print the array I get..
Array ( [0] => 1 [1] => 50 ) Array ( [0] => 2 [1] => 50 ) Array ( [0] => 3 [1] => 50 )
Where 1, 2 and 3 are the ingredient IDs.
I can remove ingredients from the array based on their ID no problem, but if I put the same ingredient in twice I won't be able to distinguish between them. I was wondering if I can add an incremental number to ID the key?
Each of the items in $_SESSION['ingredients'] already has a unique index (starting from 0 in your case). When you print your $_SESSION['ingredients'] array, you should get this:
Array ( [0] => Array ( [0] => 1 [1] => 20 ) [1] => Array ( [0] => 2 [1] => 20 ) [2] => Array ( [0] => 1 [1] => 10 ) )
Notice that each array combination has an index preceding it (starting at 0)
The following code demonstrates this:
<?php
session_start();
unset($_SESSION['ingredients']);
$_SESSION['ingredients'][] = array(1, 20);
$_SESSION['ingredients'][] = array(2, 20);
$_SESSION['ingredients'][] = array(1, 10); // adding the same ingredient again
print_r($_SESSION['ingredients']);
?>
Why not use the ingredient id as the key in the session array and then append each value to it as an element
$_SESSION['ingredients'][$_POST['ingredient']][] = $_POST['qty'];
This would give you
Array(
[1] => array(
[0] => 50,
[1] => 50
)
)
Just a thought, I don't know if this would work for your use case
change your inserted array to this:
$_SESSION['ingredients'][count($_SESSION['ingredients'])] = array($_POST['ingredient'],$_POST['qty']);
I use it in my program.

Sort a multi-dimensional array by the size of its sub-arrays

I have this multidimensional array:
Array
(
[0] => Array
(
[0] => 2012-02-26 07:15:00
)
[1] => Array
(
[0] => 2012-02-26 17:45:00
[1] => 2012-02-26 18:55:00
)
[2] => Array
(
[0] => 2012-02-26 18:55:00
[1] => 2012-02-26 17:45:00
)
[3] => Array
(
[0] => 2012-02-26 18:57:00
[1] => 2012-02-26 17:45:00
[2] => 2012-02-26 18:55:00
)
When I count subarrays I get this 1,2,2,3. How could I receive it in 3,2,2,1? I need to get for example last 3 subarrays with the highest subarray count (DESC, it means 3,2,2). How can I achieve this?
You can achieve it by utilizing usort function.
function cmp($a, $b){
return (count($b) - count($a));
}
usort($array, 'cmp');
$highest_3_sub_arrays = array_slice($array, 0, 3);
This might be what you seek:
natsort($sub_count);
$rev = array_reverse($sub_count);
$result = array_pad($rev, 3);
You might want to omit the actual sorting if the values you have are already in order.
$sizes=array();
foreach ($myarray as $k=>$v)
if (!is_array($v)) $sizes["$k"]=0;
else $sizes["$k"]=sizeof($v);
sort($sizes);
echo array_pop($sizes); //outputs 3
echo array_pop($sizes); //outputs 2
echo array_pop($sizes); //outputs 2
It seems to me that all of the other answers are working too hard. usort(), count(), and foreach() aren't necessary and when I tried natsort() it gave me: <b>Notice</b>: Array to string conversion in <b>[...][...]</b>.
rsort() will put the longest subarrays first.
Code:
$array=array(
["2012-02-26 18:55:00","2012-02-26 17:45:00"],
["2012-02-26 07:15:00"],
["2012-02-26 18:57:00","2012-02-26 17:45:00","2012-02-26 18:55:00"],
["2012-02-26 17:45:00","2012-02-26 18:55:00"]
);
$size=3; // modify this line to declare how many subarrays to capture
rsort($array); // sort the subarrays in DESC order
var_export(array_slice($array,0,$size)); // print the first n subarrays
Output:
array (
0 =>
array (
0 => '2012-02-26 18:57:00',
1 => '2012-02-26 17:45:00',
2 => '2012-02-26 18:55:00',
),
1 =>
array (
0 => '2012-02-26 18:55:00',
1 => '2012-02-26 17:45:00',
),
2 =>
array (
0 => '2012-02-26 17:45:00',
1 => '2012-02-26 18:55:00',
),
)
If you want to implement some additional sorting to break the length-ties (like between your two 2-element subarrays), then you will need to specify that in your question.

Categories