I want all rating values sum then divided with 5
array (size=2)
0 =>
object(stdClass)[571]
public 'rating' => string '3' (length=1)
1 =>
object(stdClass)[300]
public 'rating' => string '5' (length=1)
You can either use a 'foreach' block, iterate over each element in your array and sum up its 'rating' value
foreach($array->items as $item) {
$sum+=(int)$item->rating;
}
$result = $sum/5;
Or you can use the array_sum() method
$sum =array_sum((int)$array->rating);
$result = $sum/5;
PHP 7 solution:
$result = array_sum(array_column($array_of_objects, 'rating')) / 5;
you can use this code for sum array value using php . First assign variable shich store all sum value so this must set 0 and use loop for make all value sum. this is your code which help you and if your array $your_array then
$sum = 0; // this is store all sum value so first assign 0
foreach ($your_array as $rating) {
{
$sum += $rating->rating; // sum value with previous value and store it and no need to convert string type to int cause php do it
}
echo $sum; // this is final value
echo $total_sum = $sum / 5; // this is your desire result
and if your array is associative then use this code
$sum = 0; // this is store all sum value so first assign 0
foreach ($your_array as $rating) {
{
$sum += $rating['rating']; // sum value with previous value and store it and no need to convert string type to int cause php do it
}
echo $sum; // this is final value
echo $total_sum = $sum / 5; // this is your desire result
check this code and hope it will help you .
$sum = 0;
foreach($array as $val){
$sum += (int) $val->rating;
}
// divide by 5
$average = $sum/5;
for average, I think you should divide sum by no. of result like
$average = $sum/count($array);
Related
I intend to create a multidimensional array through a loop. My idea is that inside the loop function, I would assign elements into a single array, then the single array would assign into another big array before i empty the single array for the next loop process.
E.g.
for($i=0;$i<5;$i++){
$arr1['a'] = $i;
$arr1['b'] = $i+=2;
$arr2[] = $arr; //assign the arr1 into the arr2
$arr1= []; //clear arr1 again for the next looping
}
var_dump($arr2);
And the the result would be:
array (size=2)
0 =>
array (size=2)
'a' => int 0
'b' => int 2
1 =>
array (size=2)
'a' => int 3
'b' => int 5
However I find out that there are actually quite many ways to empty an array and Im not sure about that the way I empty the array is better/more efficient than the other ways such as unset or reinitialize the array like $arr1 = array()in this case. I look through online but there are not much in comparing these ways. Any suggestion to improve the performance on this or this is just as good as other ways? By looking at these:
unset($arr)
$arr = array()
$arr = []
And perhaps other ways?
Instead of making one extra array (smaller array) and then assigning the value to the bigger array, you can do something like this:
for($i=0;$i<5;$i++){
$arr2[$i]['a'] = $i;
$arr2[$i]['b'] = $i+2;
}
var_dump($arr2);
Output:
array (size=2)
0 =>
array (size=2)
'a' => int 0
'b' => int 2
1 =>
array (size=2)
'a' => int 3
'b' => int 5
In this case, you will not need to empty the (smaller) array again and again. Also it will save your memory space as you are using just one array.
If you want to execute a comparison, yo can do it with help of this code.
Ref: https://gist.github.com/blongden/2352583
It would look like so:
<?php
$calibration = benchmark(function() {
for($i=0;$i<5;$i++){
$arr2[$i]['a'] = $i;
$arr2[$i]['b'] = $i+2;
}
});
$benchmark = benchmark(function(){
for($i=0;$i<5;$i++){
$arr1['a'] = $i;
$arr1['b'] = $i+=2;
$arr2[] = $arr1;
$arr1 = [];
}
});
echo "Calibration run: ".number_format($calibration)."/sec\n";
echo "Benchmark run: ".number_format($benchmark)."/sec\n";
echo 'Approximate code execution time (seconds): '.number_format((1/$benchmark) - (1/$calibration), 10);
function benchmark($x)
{
$start = $t = microtime(true);
$total = $c = $loop = 0;
while (true) {
$x();
$c++;
$now = microtime(true);
if ($now - $t > 1) {
$loop++;
$total += $c;
list($t, $c) = array(microtime(true), 0);
}
if ($now - $start > 2) {
return round($total / $loop);
}
}
}
Output for a test run in my env (PHP 7.2.8-1+ubuntu16.04.1+deb.sury.org+1)
Calibration run: 258,534/sec
Benchmark run: 259,401/sec
Approximate code execution time (seconds): -0.0000000129
You will see that the given function by Nikhil is actually faster.
Output for the following function being run:
for($i=0;$i<5;$i++){
$arr2[$i]['a'] = $i;
$arr2[$i]['b'] = $i+2;
}
Calibration run: 209,614/sec
Benchmark run: 209,773/sec
Approximate code execution time (seconds): -0.0000000036
Feel free to play around your own tests
I have and foreach loop that outputs the totals I want to add when i echo the $val_tex it outputs in one number like "4911165" but if I echo it with a break tag it gives me the right values. It looks like
49
1
1
1
65
My question is how to get the sum of all the values which should equal "117"
$val_tex = array();
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
}
You have to add them together in the foreach loop - there's a simple way to do that $total += $keys['total']; It's just a simpler way of saying $total = $total + $keys['total'];
There are also other ways - $total = array_sum(array(1,2,3,4)); // == 10 for example. To get the sum from a single column, you get an array that only contains the values from the specific column first:
// an array of the values from that column
$arrayTotall = array_column($keys, 'total');
$total = array_sum($arrayTotals);
Your for each needs another variable to add them:
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
$sum = += $val_tex
//or...
$val_tex += $keys['total'];
//depending on how you want to us val_tex
}
The .= adds the value to previous value instead of overwriting it.
I'm using the following code to retrieve the highest 3 numbers from an array.
$a = array(1,2,5,10,15,20,10,15);
arsort($a, SORT_NUMERIC);
$highest = array_slice($a, 0, 3);
This code correctly gives me the highest three numbers array(20,15,10); however, I'm interested in getting the highest 3 numbers including the ones that are identical. In this example, I'm expecting to get an array like array(10, 10, 15, 15, 20)
Might be simpler but my brain is tired. Use arsort() to get the highest first, count the values to get unique keys with their count and slice the first 3 (make sure to pass true to preserve keys):
arsort($a, SORT_NUMERIC);
$counts = array_slice(array_count_values($a), 0, 3, true);
Then loop those 3 and fill an array with the number value the number of times it was counted and merge with the previous result:
$highest = array();
foreach($counts as $value => $count) {
$highest = array_merge($highest, array_fill(0, $count, $value));
}
You can use a function like this:
$a = array(1,2,5,10,15,20,10,15); //-- Original Array
function get3highest($a){
$h = array(); //-- highest
if(count($a) >= 3){ //-- Checking length
$c = 0; //-- Counter
while ($c < 3 || in_array($a[count($a)-1],$h) ){ //-- 3 elements or repeated value
$max = array_pop($a);
if(!in_array($max,$h)){
++$c;
}
$h[] = $max;
}
sort($h); //-- sorting
}
return $h; //-- values
}
print_r(get3Highest($a));
Of course you can improve this function to accept a dinamic value of "highest" values.
The below function may be usefull
$a = array(1,2,5,10,15,20,10,15);
function getMaxValue($array,$n){
$max_array = array(); // array to store all the max values
for($i=0;$i<$n;$i++){ // loop to get number of highest values
$keys = array_keys($array,max($array)); // get keys
if(is_array($keys)){ // if keys is array
foreach($keys as $v){ // loop array
$max_array[]=$array[$v]; // set values to max_array
unset($array[$v]); // unset the keys to get next max value
}
}else{ // if not array
$max_array[]=$array[$keys]; // set values to max_array
unset($array[$keys]); // unset the keys to get next max value
}
}
return $max_array;
}
$g = getMaxValue($a,3);
Out Put:
Array
(
[0] => 20
[1] => 15
[2] => 15
[3] => 10
[4] => 10
)
You can modify it to add conditions.
I thought of a couple of other possibilities.
First one:
Find the lowest of the top three values
$min = array_slice(array_unique($a, SORT_NUMERIC), -3)[0];
Filter out any lower values
$top3 = array_filter($a, function($x) use ($min) { return $x >= $min; });
Sort the result
sort($top3);
Advantages: less code
Disadvantages: less inefficient (sorts, iterates the entire array, sorts the result)
Second one:
Sort the array in reverse order
rsort($a);
Iterate the array, appending items to your result array until you've appended three distinct items.
$n = 0;
$prev = null;
$top = [];
foreach ($a as $x) {
if ($x != $prev) $n++;
if ($n > 3) break;
$top[] = $x;
$prev = $x;
}
Advantages: more efficient (sorts only once, iterates only as much as necessary)
Disadvantages: more code
This gives the results in descending order. You can optionally use array_unshift($top, $x) instead of $top[] = $x; to get it in ascending order, but I think I've read that array_unshift is less efficient because it reindexes the array after each addition, so if optimization is important it would probably be better to just use $top[] = $x; and then iterate the result in reverse order.
my task is to calculate average value from an array.
$arrayToTest = [[[1], 1], [[1,3,5,7], 4], [[2,5,4,1,2,3], 2.8],
[[-1,-1,-1,-1,-1], -1], [[4,23,84,12,76,34,-7,-23], 25.375]];
From inner array, so for example [1,3,5,7] and expected value is 4.
I have to use a function, I tried this:
function arrayAverage ($arrayToTest)
{
foreach($arrayToTest as $case)
foreach ($case as $item)
{
$arraySum = array_sum($item);
$arrayCount = array_count_values($item);
$average = $arraySum / $arrayCount;
return $average;
}
}
but it does not work. I feel I'm doing something wrong with calling the inner array.
Comment:
I assume that you wish to calculate the average values of the innermost arrays.
The solution below returns the average of each array - not the average of all arrays. But - of course you easily could calculate the average of all arrays.
Therefore the function arrayAverage(…) returns an array of average values instead of the average value of (only) the last array.
I declared the input array (arrayToTest) explicitely, for the reason that one can better see the array structure (array of arrays and scalars) like this.
Code:
<?php
$arrayToTest = array (
array(
array(1),
1
),
array(
array(1,3,5,7),
4
),
array(
array(2,5,4,1,2,3),
2.8
),
array(
array(-1,-1,-1,-1,-1),
-1
),
array(
array(4,23,84,12,76,34,-7,-23),
25.375
)
);
echo '<pre>'; print_r($arrayToTest); echo '</pre>';
$average = arrayAvarage ($arrayToTest);
echo '<pre>'; print_r($average); echo '</pre>';
function arrayAvarage ($arrayToTest) {
$result = array();
foreach($arrayToTest as $case) {
foreach ($case as $items) {
if (!is_array($items)) continue;
$result[] = array_sum($items) / count($items);
}
}
return $result;
}
?>
Result:
Array
(
[0] => 1
[1] => 4
[2] => 2.8333333333333
[3] => -1
[4] => 25.375
)
if your array contains internal arrays in the index 0, you can do this by:
function arrayAvarage ($arrayToTest)
{
$out_put_arr = array();
foreach($arrayToTest as $case)
{
$arraySum = array_sum($case[0]);
$arrayCount = array_count_values($case[0]);
$avarage = $arraySum / $arrayCount;
$out_put_arr[]= $avarage;
}
return $out_put_arr;
}
so the loop for the main array, each item in the main array will give you array, and int $case[0] = [1,3,5,7] and $case[1] = 4, also you shouldn't return in for loop because this will return the first average only. so you can declare new array to fill with all averages.
function average($array){
return array_sum($array) / count($array);
}
foreach($arrayToTest as $array){
echo "Average: " . average($array[0]);
}
You should look at the first element of the $case array, which is the actual place where the array with values is situated. Note that you can also use the array_sum function.
Also, you should not return just like that, because that will interrupt the function from doing anything more. So, only return when you really want to do that.
As you already have expected values, I see no reason why your function should return those averages again. Instead it could verify the correctness of these expected values, and return the index of the array when that comparison fails.
function arrayAverage ($arrayToTest)
{
foreach($arrayToTest as $index => $case) {
$average = array_sum($case[0]) / count($case[0]);
if ($average !== $case[1]) {
return $index; // not expected value
}
}
return false; // all averages are equal to expected value
}
So, the above function will return FALSE when all averages are as expected. Otherwise it will return the index of the first mismatch.
I have an array of about 100 different random number like this:
$numbers=array(10,9,5,12, ..... .... ... ...);
now i want to make an array of random numbers from this array so that addition of selected numbers will be my given number. example: i may ask to get array of numbers such that, if i add all numbers it will be 100.
i am trying to do it in this way,
function rendom_num ($array,$addition)
{
//here is the code
}
print_r (rendome_num ($numbers,100));
i am not able to fiend the code for last 3 days!
Please use shuffle-
<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
php.net
can use shuffle as #chatfun said or can try array_rand if want only some random values from your array
$value= array("Rabin","Reid","Cris","KVJ","John");
$rand_keys=array_rand($value,2);
echo "First random element = ".$value[$rand_keys[0]];
echo "<br>Second random element = ".$value[$rand_keys[1]];
Something like this should work. The breakdown is commented so you know what it's all doing.
function Randomizer($number = 100)
{
// This just generates a 100 number array from 1 to 100
for($i=1; $i <= 100; $i++) {
$array[] = $i;
}
// Shuffles the above array (you may already have this array made so you would need to input into this function)
shuffle($array);
// Assign 0 as base sum
$sum = 0;
// Go through the array and add up values
foreach($array as $value) {
// If the sum is not the input value and is also less, continue
if($sum !== $number && $sum < $number) {
// Check that the sum and value are not greater than the input
if(($sum + $value) <= $number) {
// If not, then add
$sum += $value;
$new[] = $value;
}
}
// Return the array when value hit
else
return $new;
}
// If the loop goes through to the end without a successful addition
// Try it all again until it does.
if($sum !== $number)
return Randomizer($number);
}
// Initialize function
$test = Randomizer(100);
echo '<pre>';
// Total (for testing)
echo array_sum($test);
// Array of random values
print_r($test);
echo '</pre>';