I am trying to redeem a value from the array. For example I have 20 Points and I am going to redeem from the list of earned points.
Here is my array structure which will shown as follows
$newstructure = array(
array('earnedpoints'=>'10','usedpoints'=>'0'),
array('earnedpoints'=>'25','usedpoints'=>'0'),
);
which has n number of data's(array).
I am trying to reduce the values from the earned points
Points to redeem : 20. In a foreach statement i am just
$remainingpoints=20; // Redeeming Points is named as in variable of $remainingpoints
foreach ($newstructure as $keys => $newone) {
if ($remainingpoints > $newone['earnedpoint']) {
$remainingpoints = $remainingpoints - $newone['earnedpoint'];
} else {
$remainingpoints = $newone['earnedpoint'] - $remainingpoints;
}
}
For the Point Redeeming for the first iteration of foreach earned point is 10, remaining point is 10 (based on above code) and used point is 10
For the second iteration the earned point is 25 but i want to redeem only 10 so i want to stop the loop once the redeeming values are finished (Previous Iteration 10 and Current Iteration 10)
I trying to get the result as (Redeem Point 20)
First Iteration Used Points 10 and Remaining Points is 10.
Second Iteration Used Points 10 and Remaining Points is 0.
Also I am trying to store the information as in the form of array too.
$newstructure = array(
array('earnedpoints'=>'10','usedpoints'=>'10','remainingpoints'=>'10'),
array('earnedpoints'=>'25','usedpoints'=>'10','remainingpoints'=>'0'),
);
Can anyone point me a right direction inorder to get this desired result?
First thing, in one place you use earnedpoints as your table key, and in loop you use earnedpoint.
This code should work for you:
<?php
$newstructure = array(
array('earnedpoints'=>'10','usedpoints'=>'0'),
array('earnedpoints'=>'25','usedpoints'=>'0'),
);
$remainingpoints=25; // Redeeming Points is named as in variable of $remainingpoints
foreach ($newstructure as $keys => $newone) {
if ($remainingpoints > $newone['earnedpoints']) {
$toRedeem = $newone['earnedpoints'];
}
else {
$toRedeem = $remainingpoints;
}
$remainingpoints -= $toRedeem;
$newstructure[$keys]['usedpoints'] = $toRedeem;
$newstructure[$keys]['remainingpoints'] = $remainingpoints;
/*
if ( $remainingpoints == 0 ) {
break;
}
*/
}
var_dump($newstructure);
In comment I put code where you could break your loop but when you break it, you won't have set used_points and remainingpoints for the following array values
Related
I have run into an issue where i am adding the point for a user with the previous point already stored in the table via laravel. Now I have an issue where i need to loop all the points of a specific user and I need to add in a new column for each entry the difference between the old previous point and the current point.
From the table i have first entry point is 1 , second entry point is 11, third is 21 and 4th is 22. Here what I need is, I need to loop all these data and for the first record i need to add the difference as 1 in new column and for second the difference between 1st and 2nd row are 10 and for 3rd the difference between 2nd and 3rd are again 10 and for 4th record th diff between the 3rd and 4th are 1.
Please someone provide me with a function which will help me to update new column with the difference in points based on previous and the current point
I assume you are using model
You can try this.
// $id is equal to user_id
function difference($id) {
// First get all your data
$data = YourModel::where('user_id', $id)->get();
// Loop all your data
foreach($data as $d) {
//get previous data
$last = YourModel::where('user_id',$id)->where('created_at', '<', $d->created_at)->first();
// if null then return zero else get the point
$last = isset($last) ? $last->points : 0;
// get the difference from the last
$dif = $d->points - $last;
// putting the difference to the data
$d->difference = $dif;
$d->save();
}
}
Hope this will help you...
I'm doing a little php script and i have a form that saves several things on a txt.
I need to read all the lines and take the last value of each and put them all inside an array
I was thinking that i could do that with the explode function but i don't know how to implement it several times to sum all the values and get the average.
$nombre=$_POST['nombre'];
$edad=$_POST['edad'];
$email=$_POST['email'];
$importe=$_POST['importe'];
$nombre=$_POST['nombre'];
//this part writes each value of the form to a txt file separated by an " | "
// this is where I need help. I have to show the sum of all the $importe values in all of the lines in the txt
//
$miarchivo=fopen("resultados.txt","a");
if(!($miarchivo))
{
print("Imposible abrir archivo");
exit;
}
fputs($miarchivo," $nombre | $edad | $email | $importe \n" .PHP_EOL);
fclose($miarchivo);
//echo "<script>location.href='forma.php'</script>";
//This part only shows the values of the txt after the script ends
$miarchivo=fopen("resultados.txt","r");
if
(! ($miarchivo))
{
print("no hay resultados");
exit;
}
while(!feof($miarchivo)){
$linea=fgets($miarchivo,255);
print"$linea<BR>";
}
fclose($miarchivo);
I expect to get an array like:
tab [0] $importe //from line 0
tab [1] $importe //from line 2
tab [2] $importe //from line 3
tab [3] $importe //from line 4
So i can sum all of them and get the average in other variable
Export to array then take last value and store in array. Finally add the array and get the average result. Here is your code
while(!feof($miarchivo)){
$linea=fgets($miarchivo,255);
$quantityArray[] = end(explode('|',$linea));
}
$averageResult = array_sum($quantityArray)/count($quantityArray);
You need to make $linea[] an array by adding brackets like this.
while(!feof($miarchivo)){
$linea[]=fgets($miarchivo,255);
}
Then you can access each line like this...
$linea[0] = "line 1"
$linea[1] = "line 2"
if you need to print the current line, like you do in your while loop, you can add another temporary variable and print that like this...
$linea[] = $currentLine = fgets($miarchivo,255);
print($currentLine);
You don't need to store the values in an array to get an average. Unless you need to do something else with that array, it's just a waste of memory. You can sum and count the $importe values as you read the lines, and then calculate the average from those values at the end.
$count = $sum = 0;
while (($linea = fgetcsv($miarchivo, 0, '|')) !== false) {
$importe = trim($linea[3]);
$count++;
$sum += $importe;
}
if ($count) { // check count to prevent division by zero
$average = $sum / $count;
}
I have two arrays. One array $People currently creates number of 44 individuals. Lets just assume currently its
$People = array('1','2',...,'44');.
I have another array of 15 elements.
$Test = array('A','B',...'O');
Now I want to be able to assign the test randomly to each individual. I know how to do this using random function in php.
Where it has got tricky for me and what I need help with is how can I even out the test array. What I mean by this is since there are currently 44 individuals (this array will grow in future), what I want is 14 test versions to have 3 individuals and 1 version would have 2. So I want the test array to even out. I also want it to handle as growth of $People array.
Ex: Test Version D will have individual '4', '25'. Every other version has three random individuals.
Few ideas I came up with are things like running random integer on $Test array and which ever gets highest/lowest gets 2 individuals and rest three. This would give a problem when I increase the size of $People array; to deal with that I though about using modulus to figure out what will be even number of $Test beforehand.
I can do this and other ideas but am pretty sure there has to be a better way to do this.
Clarifying your situation:
You want to distribute the values inside $People randomly amongst your $Test array. The problem you stated you are having is that the amount of values in $People isn't always perfectly dividable by the amount of values in $Test, and you aren't sure how to go about implementing code to distribute the values evenly.
Proposed solution:
You could obtain the values in a foreach loop randomly 1 by 1 from a shuffled version of $People and put them in a new array called $Result. You would also have a conditional checking if you have extracted all the values from the shuffled $People array: if($count>=$arrayCount) where $arrayCount=$count($shuffledPeople);. If you have obtained all the values, you first make the $bool value false (in order not to iterate through the while loop anymore, and then you break; out of the foreach loop.
$Result =[];//the array containing the results
$shuffledPeople = $People;
shuffle($shuffledPeople);//mixing up the array
$arrayCount = count($shuffledPeople);//finding the total amount of people
$count = 0;
$bool = TRUE;
while ($bool)
{
foreach($Test as $value)
{
$Result[$value][] = $shuffledPeople[$count];
$count++;
if ($count>=$arrayCount)
{
$bool = FALSE;
break;
}
}
}
To view the results, all you would need to do is:
foreach ($Result as $key => $value)
{
echo "{$key}: <br>";
if (is_array($value))
{
foreach ($value as $something)
{
echo "-->{$something}<br>";
}
}
else
{
echo "-->{$value}<br>";
}
}
I believe that this is what you want to do...
Assume that you have $people and $test arrays. You want to know how many people per test...
$ppt = ceil(sizeof($people)/sizeof($test));
Now, $ppt is the people per test. The next step is to shuffle up the people so they are randomly assigned to the tests.
shuffle($people);
Now, we can chunk up the people into sub-arrays such that each sub-array is assigned to a test. Remember, the chunks are random now because we shuffled.
$chunks = array_chunk($people, $ppt);
Now, everyone in $chunks[0] will take $test[0]. Everyone in $chunks[1] will take $test[1]. Everyone in $chunks[2] will take $test[2].
I have a two-dimensional array with two key values, [program] and [balance], created by a MySQL SELECT statement in WordPress. I know what the values of [program] will be (they never change) - it's the balances I'm interested in.
For example:
*[program] = 'Sales', [balance] = 10,000*
*[program] = 'Commission', [balance] = 1,250*
All I want to do is assign the balance value to a variable, so I will have:
*$sales = (the balance for the Sales program)*
*$commission = (the balance for the Commission program)*
I know I'm being thick here, but I cannot see how to do this after about an hour of searching and screwing around with php. It's a total brain block and all the references I can find online talk about loops and echoing all the values and stuff.
Would appreciate a de-blocking!
//make a function
function findBalanceByProgram($inputArray,$program)
//loop trough all the keys on the first dimension
foreach($inputArray as $val){
//check in the second dimension if your program is the same as the program you are checking for
if($val['program']==$program)
//if so.. return the value and jump out of the function
return $val['balance'];
}
}
//an example of use.
echo findBalanceByProgram($yourArray,'sales');
I'm trying to get every output out of a json file. So far I have:
$json_feed = file_get_contents($indy_feed_url);
$json_items = json_decode($json_feed, TRUE);
$individual = $json_items['indy'][0];
and then echo things out.
This works fine for item 0. However, I want to do all items.
The number of items in the json file varies from time to time so I cannot just enter like 10 here because sometimes there might be 20 or 5 etc.
How can I do this in a loop so that it counts the number of items and loops that many times?
Use the foreach statement:
foreach($json_items['indy'] as $item) {
// do whatever you want with $item
}