Given an array and I need to to display the average after every seventh row
Array
(
[0] => Array
(
[date] => 01-03-2015
[site_id] => 1
[starting_reading] => 567
[close_reading] => 567
)
[1] => Array
(
[date] => 03-03-2015
[site_id] => 1
[starting_reading] => 567
[close_reading] => 567
)
[2] => Array
(
[date] => 08-03-2015
[site_id] => 1
[starting_reading] => 567
[close_reading] => 567
)
)
Now what i need, is to display all avg reading in 7 days like:
1 to 7
--------------------- avg=close-start----------
8 to 14
--------------------- avg=close-start----------
15 to 21
--------------------- avg=close-start----------
22 to 28
--------------------- avg=close-start----------
29 to 31
--------------------- avg=close-start----------
date starting_reading close_reading
01-03-2015
03-03-2015
--------------------- avg=close-start----------
08-03-2015
--------------------- avg=close-start----------
//$arr is as the array you described
foreach($arr as $k => $v){
//$k will be some integer 0...count($arr)-1 assuming a 'normal' index
//$v is your child array, where you can access attributes such as $v['date']
//every seventh row can be done in a number of ways, the easiest way is:
if($k % 7 == 0){
//then show new line. This will happen every time the number divides into seven. 0, 7, 14, 21... etc.
var_dump($v); will output your child of the seventh (multiple) item
}
}
Including your example for dates and averages assuming array is correctly formatted
//$arr is as the array you described
$close = 0;
$start = 0;
foreach($arr as $k => $v){
//$k will be some integer 0...count($arr)-1 assuming a 'normal' index
//$v is your child array, where you can access attributes such as $v['date']
//every seventh row can be done in a number of ways, the easiest way is:
if($k % 7 == 0){
$close = 0; //reset close
$start = 0; //reset start
}
$close += (int)$v['close_reading'];
$start += (int)$v['starting_reading'];
if(($k + 1) % 7 == 0){ //this is the last row, 6, 13, 20 etc.
echo ($k-5).' to '.($k+1);
echo 'Average: '.(($close - $start) / 7);
}
}
Related
I have an array of 20 different numbers which contains ranking of students.
I want to split this array into two sub arrays of equal length i.e 10
I also want the sum of all numbers within each array to be close.
For example, in sub-array A there could be a total sum of 56 and in sub-array B there could be a total sum of 57.
I am using PHP.
I sort the main array here and would like to assign index[0] to sub-array A and index[1] to sub-array B, and keep repeating this until both arrays are filled.
My approach works but i think its not great and not dynamic.
I interate through the main original array for [i] and then add that to the first sub-array, then I set i = i+2 so that I get every second value and store them in the first array.
I then remove the value at index[i] from the main array.
What is left over is now sub-array B.
$kids = array (8,5,6,9,3,8,2,4,6,10,8,5,6,1,7,10,5,3,7,6);
sort($kids);
$arrlength = count($kids);
for($x = 0; $x < $arrlength; $x++) {
echo $kids[$x];
echo "<br>";
}
$teamA = array();
$teamB = array();
$i = 0;
while ($i < $arrlength)
{
#echo $kids[$i] ."<br />";
array_push($teamA, $kids[$i]);
unset($kids[$i]);
$i += 2;
}
$teamB = $kids;
print_r($teamA);
print_r($teamB);
My Output is :
Array ( [0] => 1 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 6 [6] => 7 [7] =>
8 [8] => 8 [9] => 10 )
The sum here of all values is = 58
Array ( [1] => 2 [3] => 3 [5] => 5 [7] => 5 [9] => 6
[11] => 6 [13] => 7 [15] => 8 [17] => 9 [19] => 10 )
The sum here of all values is = 61
Any help is greatly appreciated. I have no real experience with PHP or its built in functions so sorry if this is a basic question. Thanks!
There is a built-in helper function of php, array_slice. You can read about it in the link I provided.
Here's how you can use in to achieve what you want:
$kids = array (5,7,6,8,3,8,2,4,6,10,8,5,6,10,7,6,5,3,7,6);
sort($kids);
$arrlength = count($kids);
$arrayA= array_slice($kids, 0, $arrlength / 2);
$arrayB= array_slice($kids, $arrlength / 2);
Output
// $arrayA
array:10 [▼
0 => 2
1 => 3
2 => 3
3 => 4
4 => 5
5 => 5
6 => 5
7 => 6
8 => 6
9 => 6
]
// $arrayB
array:10 [▼
0 => 6
1 => 6
2 => 7
3 => 7
4 => 7
5 => 8
6 => 8
7 => 8
8 => 10
9 => 10
]
Another approach for achieving what you asked
$kids = array(8,5,6,9,3,8,2,4,6,10,8,5,6,1,7,10,5,3,7,6);
sort($kids);
$teamA = array();
$teamB = array();
foreach($kids as $i => $kid){
if($i % 2){
array_push($teamA, $kid);
} else{
array_push($teamB, $kid);
}
}
It will generate the same output and sum as you want.
The array is like this
$a = array(1,2,3,4,5,6,7,8);
After that in each iteration the 3rd element should be removed until it reaches to a single element
the iteration will be something like this
index:0 1 2 3 4 5 6 7
value:1 2 3 4 5 6 7 8
this is the normal one
index:0 1 2 3 4 5 6 7
value:1 2 4 5 7 8
here 3 and 6 removed as they came out as the 3rd elements
then after 6 is removed it should count 7 and 8 as 1st and 2nd and go to value 1 which makes 1 as the 3rd element.This continues until there is only one element remaining.
output
12345678
1245678
124578
24578
2478
478
47
7
7 is the remaining element
here is the code, hope it helps.
<?php
$array = [1,2, 3,4,5,6,7,8];
function removeAtNth($array, $nth)
{
$step = $nth - 1; //gaps between operations
$benchmark = 0;
while(isset($array[1]))
{
$benchmark += $step;
$benchmark = $benchmark > count($array) -1 ? $benchmark % count($array) : $benchmark;
echo $benchmark."\n";
unset($array[$benchmark]);
$array = array_values($array);
echo implode('', $array)."\n";
}
}
removeAtNth($array, 3);
result:
kris-roofe#krisroofe-Rev-station:~$ php test.php
1245678
124578
24578
2478
478
47
7
Your looking for array_chunk()
$a = array(1,2,3,4,5,6,7,8);
$thirds = array_chunk($a, 3);
$thirds now is like:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
)
)
Then just loop through the $thirds array and array_pop() to grab the last value.
However, I'm not sure why you're looking to get 7 at the end and not 8. Can you explain?
I have a query that returns a list of rows from mysql database, the list of rows generated have of rows values being the same.
Table
id mAmount paidAmount
1 100 50
1 100 30
2 200 20
2 200 150
I actually want to sum the paidAmount and subtract from just one of mAmount value per the same id.
For instance
1 | (100) - (50 + 0) = 50 |
1 | (100) - (30 + 50) = 20 |
2 | (200) - (20 + 0) = 180 |
2 | (200) - (150 + 20) = 30 |
I do not want anyone any to give me the entire codes to this, but an idea as to how to go about it using either php with while loop or possibly foreach statements. Thanks really appreciate.
Just have to loop and accumulate the paid amount, then do the subtraction.
For this example I suppose you pre-order your records by id and pass the records to an multidimensional array called rows:
$currentId = $rows[0]['id'];
$accumulated = 0;
foreach ( $rows as $row ) {
if ( $row['id'] != $currentId ) {
$accumulated = 0;
$currentId = $row['id'];
} // end if not current id
$accumulated += $row['paidAmount'];
$balance = $row['mAmount'] - $accumulated;
$row['balance'] = $balance;
$result[] = $row;
} // end foreach
print_r ( $result );
Results are printed like this:
Array
(
[0] => Array
(
[id] => 1
[mAmount] => 100
[paidAmount] => 50
[balance] => 50
)
[1] => Array
(
[id] => 1
[mAmount] => 100
[paidAmount] => 30
[balance] => 20
)
[2] => Array
(
[id] => 2
[mAmount] => 200
[paidAmount] => 20
[balance] => 180
)
[3] => Array
(
[id] => 2
[mAmount] => 200
[paidAmount] => 150
[balance] => 30
)
)
I have two arrays of numbers, one containing a lot of numbers, one only a few. There are no duplicates within or between arrays:
$all = range(1, 50);
$few = array(7, 11, 19, 27, 29, 36, 40, 43);
$many = array_merge(array_diff($all, $few));
I now want to calculate the differences between each of the "few" numbers and all of the "many" that follow it but come before the next of the "few". For example, among $many, only 28 falls between 27 and 29 from $few, so I want to calculate the difference between 28 and 27. No other differences to 27 are calculated, because no other $many fall between 27 and 29. For 19 from $few I will calculate the differences to 20, 21, 22, 23, 24, 25 and 26, because they all lie between 19 and the next number from $few, which is 27.
To calculate the differences, I use loops. Here is a somewhat simplified code (which ignores the fact that there is no index [$i + 1] for the last number in $few):
$differences = array();
for($i = 0; $i < count($few); $i++) {
foreach($many as $m) {
if($m > $few[$i] && $m < $few[$i + 1]) {
$differences[] = $m - $few[$i];
}
}
}
If I have huge arrays, the loops will take a long time to run. So:
Is there a better way to calculate the differences, without using loops?
The resulting $differences looks like this:
Array $many $few
( ↓ ↓
[0] => 1 // 8 - 7 = 1
[1] => 2 // 9 - 7
[2] => 3 // 10 - 7
[3] => 1 // 12 - 11
[4] => 2
[5] => 3
[6] => 4
[7] => 5
[8] => 6
[9] => 7
[10] => 1
[11] => 2
[12] => 3
[13] => 4
[14] => 5
[15] => 6
[16] => 7
[17] => 1
[18] => 1
[19] => 2
[20] => 3
[21] => 4
[22] => 5
[23] => 6
[24] => 1
[25] => 2
[26] => 3
[27] => 1
[28] => 2
)
My basic reasoning is that as a human, I don't see two arrays that I compare:
... 16 17 18 | 20 21 22 23 24 25 26 | 28 29 30 31 ...
exclude | include | exclude
19 (27)
But rather one number line that I go along from one number to the next, and when I meet one marked "few" I will calculate all the differences to each of the following numbers, until I meet another one marked "few":
... 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ...
... m m m f m m m m m m m f m m m m ...
↑ ↑ ... ↑
start calculate stop
Because it is sorted, I don't have to go over the whole $many-array number by number for every number from $few. So can we somehow take the fact into account that the arrays are ordered? Or maybe build one array that contains the markers ("f", "m") and the numbers as keys? E.g.:
$all = array("drop this", "m", "m", "m", "m", "m", "m", "f", ...);
unset($all[0]); // drops the first element with index 0
Apart from the two calls to sort(), all you need is a single loop through $many.
// Input data provided in the question
$all = range(1, 50);
$few = array(7, 11, 19, 27, 29, 36, 40, 43);
$many = array_values(array_diff($all, $few));
// Display the values to see what we are doing
echo('$few = ['.implode(' ', $few)."]\n");
echo('$many = ['.implode(' ', $many)."]\n");
//
// The actual algorithm starts here
// Sort both $few and $many
// it works fast enough and it is required for the rest of the algorithm
sort($few);
sort($many);
// Be sure the last value of $few is larger than the last value of $many
// This is needed to avoid extra checking for the last element of $few inside the loop
if (end($few) < end($many)) {
array_push($few, end($many) + 1);
}
// Extract the first two items from $few
$current = array_shift($few);
$next = array_shift($few);
// This is the result
$differences = array();
// Run only once through $many, check each item against $next
// subtract $current from it; advance when $next was reached
foreach ($many as $item) {
// Skip the items smaller than the first element from $few
if ($item < $current) {
continue;
}
// If the next element from $few was reached then advance to the next interval
while ($next < $item) {
$current = $next;
$next = array_shift($few);
}
// Here $current < $item < $next
// This echo() is for debug purposes
echo('$current = '.$current.'; $item = '.$item.'; $next = '.$next.'; difference='.($item - $current)."\n");
// Store the difference
$differences[] = $item - $current;
}
I have a script that builds an array of week numbers for the last 12 weeks like so:
$week_numbers = range(date('W'), date('W')-11, -1);
However, if the current week number is 1, then this will return an array like so:
Array
(
[0] => 1
[1] => 0
[2] => -1
[3] => -2
[4] => -3
[5] => -4
[6] => -5
[7] => -6
[8] => -7
[9] => -8
[10] => -9
[11] => -10
)
But I need this array to look like this instead:
Array
(
[0] => 1
[1] => 52
[2] => 51
[3] => 50
[4] => 49
[5] => 48
[6] => 47
[7] => 46
[8] => 45
[9] => 44
[10] => 43
[11] => 42
)
Can anyone see a simple solution to this?
I have thought about doing something like this (not tested):
$current_week_number = date('W');
if($current_week_number<12){
// Calculate the first range of week numbers (for current year)
$this_year_week_numbers = range(date('W'), 1, -1);
// Calculate the next range of week numbers (for last year)
$last_year_week_numbers = range(52, 52-(11-$current_week_number), -1);
// Combine the two arrays to return the week numbers for the last 12 weeks
$week_numbers = array_merge($this_year_week_numbers,$last_year_week_numbers);
}else{
// Calculate the week numbers the easy way
$week_numbers = range(date('W'), date('W')-11, -1);
}
one idea
$i = 1;
while ($i <= 11) {
echo date('W', strtotime("-$i week")); //1 week ago
$i++;
}
if you arent scared of loops you can do this:
$week_numbers = range(date('W'), date('W')-11, -1);
foreach($week_numbers as $key => $value) { if($value < 1) $week_numbers[$key] += 52; }
You can do a modulo % trick:
$week_numbers = range(date('W'), date('W')-11, -1);
foreach ($week_numbers as $i => $number) {
$week_numbers[$i] = (($week_numbers[$i] + 52 - 1) % 52) + 1;
}
// -1 +1 is to change the range from 0-51 to 1-52
I've found that using modulo like this is often useful for date calculations, you can something similar for months, using 12.
Well, I think the easiest way is to create array after getting dates:
$week_numbers = array_map(function($iDay)
{
return ($iDay+52)%52?($iDay+52)%52:52;
}, range(date('W'), date('W')-11));
-note, that you can not do just % since 52%52 will be 0 (and you want 52)