e.g. if I pass $total = 2 then it should calculate the sum of first
two arrays.
sub1 + sub2
**HERE IS MY CODE **
<?php
$num = 2;
$array = array();
$total = 2;
for($x=1;$x<=$num;$x++)
{
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$array[] = $result;
}
echo '<pre>'; print_r($array);
?>
try
<?php
$array = array();
$total = 2;
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$temp_array = array_slice($result, 0, $total);
$sum = array_sum($temp_array);
print_r($result);
echo "sum of $total array is : ".$sum;
Output would be like :
Array
(
[sub1] => 30
[sub2] => 19
[sub3] => 56
[sub4] => 47
[sub5] => 6
)
sum of 2 array is : 49
https://eval.in/539097
should do the trick. hope it helps :)
simply you can use for loop like this
$sum=0;
for($i=0;$i<$total;$i++){
$sum+=$result[$i];
}
Related
So what I want to do is get all values from query and add them together to get a total amount. The following function grabs all values necessary. (Added for clarity)
public function priceTotal($conn, $var, $hours){
$query = "SELECT hour_rate, day_rate, item_id, hourly_rental FROM products WHERE item_id = :id";
$stmt = $conn->prepare($query);
$stmt->bindParam(":id", $var);
$stmt->execute();
$result = $stmt->fetchAll();
if($stmt->rowCount() > 0){
$total = 0;
foreach($result as $row){
$hour_rate = $row['hour_rate'];
$day_rate = $row['day_rate'];
if($hours == '2'){
$total += $hour_rate;
}else{
if($row['hourly_rental'] == '1'){
$hours -= 2;
$total += $hour_rate + $day_rate * $hours;
}
else{
$total = $hour_rate + $day_rate;
}
}
$array[] = $total;
}
return $array;
}
return false;
}
Now what I need to be able to do is grab the values from the array and add them all together. This was my latest attempt. But only the items in the last array get added together.
$weeklyGross = $chart->getChartInfo($conn, $weekly);
if(!empty($weeklyGross)){
foreach($weeklyGross as $row){
$hours = $row['total_hours'];
$totalItems = $row['requested_items'];
$delivery_cost = $row['delivery_cost'];
//Store total items in array
$items = explode(',', $totalItems);
$item_name = array();
$totalPrice = 0;
foreach ($items as $var){
//Get items from price total function
$addItems = $chart->priceTotal($conn, $var, $hours);
//$completeOrder = array_merge($addItems);
print_r($addItems);
foreach($addItems as $k){
$totalPrice += $k;
}
}
$totalPrice += $delivery_cost;
}
print_r($totalPrice);
}
Here is the printout of the arrays, and the values that I would like to add all together.
Array (
[0] => 420
[1] => 200
)
Array (
[0] => 270
)
Array (
[0] => 350
[1] => 350
)
Array (
[0] => 270
)
Array (
[0] => 220
)
Array (
[0] => 280
)
Array (
[0] => 270
[1] => 300
)
Array (
[0] => 700
[1] => 380
)
See what I have done with $totalPrice
$weeklyGross = $chart->getChartInfo($conn, $weekly);
if(!empty($weeklyGross)){
$totalPrice = 0; // << Put this here
foreach($weeklyGross as $row){
$hours = $row['total_hours'];
$totalItems = $row['requested_items'];
$delivery_cost = $row['delivery_cost'];
//Store total items in array
$items = explode(',', $totalItems);
$item_name = array();
/// $totalPrice = 0; // << not here, as it resets the total price on each loop
foreach ($items as $var){
//Get items from price total function
$addItems = $chart->priceTotal($conn, $var, $hours);
//$completeOrder = array_merge($addItems);
print_r($addItems);
foreach($addItems as $k){
$totalPrice += $k;
}
}
$totalPrice += $delivery_cost;
}
print_r($totalPrice);
}
I have an array like this
Array
(
[14] => 2
[28] => 1
)
what i need is an array with index value upto 31 where in ,except index 14 and 28 the value should be 0(zero) and the index 14 and 28 should have the value 2 and 1 respectively.
please help me with this.
thanks in advance
There are more ways how to do it, for example:
<?php
$arr = array(14 => 2, 28 => 1);
$res = array();
for ($i = 0; $i <= 31; $i++) {
$res[$i] = isset($arr[$i]) ? $arr[$i] : 0;
}
echo '<pre>';
print_r($res);
Do you want like this:-
<?php
$a = array_fill(0, 31, 0);
$a[14] = 2;
$a[28] = 1;
print_r($a);
?>
Output:- https://eval.in/913931
Reference:- PHP: array_fill - Manual
If I have this array:
Array (
[0] => Array (
[booking_id] => 1
[booking_status] => confirmed
[client_name] => Bale
[client_firstname] => Gareth
[days] => Array (
[day_id] => 2016-11-23,2016-11-24
[room_id] => 2
)
)
)
How can I get the number of item into day_id please?
You can use array_reduce to iterate through array items and get a final result. Take a look at this:
function reduce_func($carry, $item){
if (isset($item['days']) && !empty($item['days']['day_id'])){
$carry += count(array_unique(array_filter(explode(',', $item['days']['day_id']))));
}
return $carry;
}
$result = array_reduce($arr, "reduce_func", 0);
Update
note that you can also provide a callback to the array_filter to filter out your desired entries to be counted, eg. regex checking each entry to be a valid date. Here's PHP manual for array_filter.
$sum = 0;
foreach ($data as $booking) {
$sum += sizeof(explode(",",$booking["days"]["day_id"]));
}
$sum =0;
for ($count = 0; $count < count($data); $count++) {
$booking = $data[$count];
$day_ids = explode(",", $booking['days']['day_id'];
$sum = $sum + count($day_ids);
}
I'm struggling with this for a while now and getting more important at the moment.
Lets say we have a array with the values
Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
)
when i loop this array in a foreach loop i want the first result 11 second result 36 (11 + 25) 3rd result 38 (11 + 25 + 2) 4rd result 45 (11 + 25 + 2 +7) etc....
this way i get cumulative results
This is what i tried so far:
<?php
foreach(array_slice(weeks($start_week), 0, 26) as $week):
$gewasregistratie["gezette_vruchten_cumulatief"][$week] = $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week] + $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week-1];
$gewasregistratie["gezette_vruchten_cumulatief"][$week] += $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week];
endforeach;
foreach(array_slice(weeks($start_week), 0, 26) as $week):
echo "<td week='".$week."' class='part1'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
foreach(array_slice(weeks($start_week), 26, 51) as $week):
echo "<td week='".$week."' class='part2'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
?>
Can someone help me in the right direction ?
Simple like boiling a egg. Try this code
$test = array(11,25,2,7);
$count = 0;
foreach($test as $i=>$k)
{
$count +=$k;
echo $count." ";
}
Output:
11 36 38 45
Suggestion: you can store output in another array also.
Try this:
$a = array(11,25,2,7);
$c = 0;
foreach($a as $k=>$v){
$c += $v;
$b[] = $c;
}
print_r($b);
you will get result in array like below :
Array ( [0] => 11 [1] => 36 [2] => 38 [3] => 45 )
The simplest way
$original = array(23, 18, 5, 8, 10, 16);
$total = array();
$runningSum = 0;
foreach ($original as $number) {
$runningSum += $number;
$total[] = $runningSum;
}
var_dump($total);
$array = array( 11, 25, 2, 7 );
$results = array();
foreach ($array AS $i => $v) {
if (empty($results)) {
$results[] = $v;
} else {
$results[] = $v + $results[$i - 1];
}
}
Something like this.
Try this code
$arr=Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$sum=0;
foreach($arr as $k=>$val)
{
echo "<br>".$sum+=$val;
}
Find below solution
$arr = array(11,25,2,7);
$sum =0;
foreach($arr as $val){
$sum +=$val;
echo $sum ."<br/>";
}
If you are looking to iterate over a single-dimensional array as your question was initially worded, array_map would be your most efficient method:
function cascade($n) {
static $current = 0;
return $current += (int) $n;
}
$test = array(11,25,2,7);
$result = array_map('cascade', $test);
/**
* You could also assign back to the original array like:
* $test = array_map('cascade', $test);
*/
If you are looking to do something in a multi-dimensional array, using array_walk would be the solution there. Would you like an example?
Try this.
$myArray = Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$total = 0;
for($i=1; $i <= count($myArray); $i++) {
$total += $myArray[$i];
echo $total . ", ";
$cumulativeArray[] = $total;
}
print_r($cumulativeArray);
What would be the most efficient way of counting the number of times a value appears inside an array?
Example Array ('apple','apple','banana','banana','kiwi')
Ultimately I want a function to spit out the percentages for charting purposes
(e.g. apple = 40%, banana = 40%, kiwi = 20%)
Just put it through array_count_values. The percentages should be easy...
$countedArray = array_count_values($array);
$total = count($countedArray);
foreach ($countedArray as &$number) {
$number = ($number * 100 / $total) . '%';
}
Use array_count_values():
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
$a = Array ('apple','apple','banana','banana','kiwi');
$b = array_count_values($a);
function get_percentage($b,$a){
$a_count = count($a);
foreach ($b as $k => $v){
$ret[$k] = $v/$a_count*100."%";
}
return $ret;
}
$c = get_percentage($b,$a);
print_r($c);