PHP Calculation in variables from foreach output - php

I have this code:
$fookerdos = '';
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos .= file_get_contents($someposoA);
//to print them i you want
print $fookerdos;
So my problem that for this code will outputs many numbers becouse of many files.
for example will out output this
3.5 -6.7 6.68 -0.2 and so on..
now i want all this numbers to make them (addition)
i know how to addition some 2-3 variables, but i additions many numbers that I even dont know how many they are.
for example
print "3.5 + "-6.7" "6.68" "-0.2";
Thx :)

Does each file contain only a single number, or can they have more than one numbers?
From your previous edits, it seems as if one file contain only a number.
In that case, you can store the values in an array and sum the numbers using array_sum() or perform any other calculation as needed.
Here is a sample code for you:
$fookerdos = array ();
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos[] = file_get_contents($somekerdos);
}
echo array_sum ($fookerdos);

Related

microtime() or hrtime() for generating a unique number in a foreach loop

This has been asked before I think, but with key differences in the details...
So I want to group an array of product sub-arrays by a specific grouping value found in some sub-arrays. The grouping value, however, isn't set for all of them, only for those that are grouped together... This may sound a bit confusing so far, but I promise it'll get clearer when you take a look at the code below... So I'm doing this:
$grouped = array();
$i = 0;
foreach ($items as $k => $item) {
if ($items[$k]['ITEM.GRPCODE']) {
$groups[] = $items[$k]['ITEM.GRPCODE'];
} else {
$i++;
}
$group = $item['ITEM.GRPCODE'] ? $item['ITEM.GRPCODE'] : md5(microtime());
$grouped[$group][] = $item;
}
echo 'Groups: ' . count(array_unique($groups)) . ' - Single: ' . $i . '<br />';
echo count($grouped) . '<br /><pre>' . print_r($grouped, true) . '</pre>';
At this point I should mention that I already know, for the current dataset, how many are the ones that are grouped together and how many are the single ones (the code I used to calculate each kind is also found in the code above)... So for an unchanged number of Groups/Single of 314/238 (the first echo), after a number of page refreshes I noticed that count($grouped) (the second echo) fluctuated from 552 (the sum of the two numbers above) to other values less than that, like 545, 547, 551, making it obvious that $group, when calculated by md5(microtime()) had produced 2-3 identical values, thus grouping products together that shouldn't be grouped together otherwise... Maybe the loop was so instant that even microtime() couldn't handle it? Then after some research I replaced md5(microtime()) with md5(hrtime(true)) and this time after A LOT of page refreshes I kept getting 314/238 for the first echo and 552 for the second one, which means that I was getting the expected groups every time...
So what's happening here? Is it that the loop was so instant that microtime() couldn't handle it? Is it that hrtime() is so more precise than microtime()? Is it something else?
Can you please share your thought and shed some light on this? Additionally, if neither md5(microtime()) nor md5(hrtime(true)) is the proper way to produce unique numbers in a foreach loop, could you give me another idea on how to do it better? Thanks in advance.

How do you set up an array to hold '0's for empty locations so graphs(Highcharts) can format them correctly?

I'm trying to get my Highcharts graph to work. The Reason I'm having so much trouble with it this time is because I have to keep the program adaptable for future changes when it comes to my columns(named issues1 through 12).
The Goal is pretty simple, I just need to grab the issues between hours 1-12 during a certain time period, then create a graph.
My idea Is that I should create a view that organizes the desired information because there is a lot more to that table that I left out, and then create an SQL to organize the data from there. Which I realize might be overkill, but I'm an intern and my supervisor probably did it to help make it simple for me.
There are 4 different places I need to use SQL to make the Table work.
X-Axis
Day shift numbers
Swing shift numbers
Night shift numbers
So for my code The X-Axis, It works fine for just calling in the names.
xAxis: {
categories: [
<?php
foreach ($xAxisresult as $Xrow) {
echo "'" . $Xrow['IssueName'] . "'" . ',';
}
?>
]
I believe the Day/Swing/Grave SQL statements should all be similar so I'm just going to focus on one. But this is where the problem starts with how I have it set up. I tried to run an If statement were I compare the two arrays I have set up and try to match the IssueName Columns.
name: 'Day',
data: [
<?php
foreach ($Dresult as $Drow) {
if ($Xrow['IssueName'] == $Drow['IssueName']){
echo $Drow['Issues'] . ',';
}
else{
echo $Drow['Issues'] . ',';
}
}
You guys can most likely see a lot of whats wrong here. But I need to make a loop or array that will find out that if there is an empty spot in the array and output a 0 so the data stays correct.
Sorry for the wall of Text, I just wanted to give you guys as much information as possible.
To answer your question how to create an array that holds zero values and merge with the data array (I assume).
You can use array_fill to create the array with zeros, and use array_replace to replace with the data array.
$arr = array_fill(0, 10, 0); //[0,0,0,0,0,0,0,0,0,0]
$data = [2 => 15, 5 =>10, 7 => 16]; // your data
$new = array_replace($arr, $data);
var_dump($new); // [0,0,15,0,0,10,0,16,0,0]

Assign random but even amount from an array to a list array in PHP?

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].

Storing formatted variable into MySQL DB?

I had this working by simply passing the data from one variable to another like so:
$CalcsSets = $DisplayCalcs;
without the need to use the loop inside the first if() statement and it inserted the data without quotes but all of a sudden it's stopped working and I'm not sure why (it only started showing last integer), so I went with the more complex code trying to get it to work again as shown below.
Here's the complex code I'm working with:
for($i=1; $i<=$CalcSets; $i++){
$calculations = PerformCalc($min, $highest, $OperatorType);
echo 'Calculations performed for '.$SetText[$i];
foreach ($calculations as $key => $DisplayCalcs) {
echo $SetCalc[] = $DisplayCalcs.', '; //stores calculations with ',' in
//array.
}
if($CalcSets == 1){
for($i=0;$i<$CalcSets;$i++){
$SetResults = $SetCalc[$i];
echo '<strong>'.(string)$SetResults.'</strong>';
}
DB_Insert($SetResults);
}
What it's supposed to do is insert values in the following format (1,2,3,4,5,) into the database in a VARCHAR row but now all it shows is the last integer with no comma. I originally wanted to just store the integers and not a comma but I couldn't get it to display on the page with commas after each integer so I went this route as mentioned earlier.
I realize I'm probably going about this the wrong way, but if any of you know a much easier, and shorter, way to do what I want, I'd be extremely appreciative of the help.
Reason I'm doing it this way, is because on the results page, it needs to show in the format mentioned above.
FYI, I did check the DB row and it is still set to VARCHAR with a length of 10 at the moment.
UPDATE TO MAKE INTENTIONS MORE CLEAR
Ok, I'm going to go back to square one and try to make my intention as clear as possible. I've been rewriting this code snippet more times than I care to count and my brain is all foggy lol.
array1 = array(1, 2, 3, 4, 5, 6);
foreach(array1 as $key => $data){
echo $data.',';
// will display 1,2,3,4,5,6, in browser.
}
if(is_true == 1){
INSERT ALL $data values into DB here.
}
That's what I'm trying to accomplish in it's simplest form, I'm just have extreme difficulty achieving my goal.
Second Update - Topic Solved
Apparently, the DB field had to be set to Text rather than VarChar. I guess we learn something new everyday.
Again, thanks everyone for all of your help. It was greatly appreciated!
I'm sorry but I couldn't make much sense from the original code but focusing only on the last IF and the containing LOOP, I think the problem is with the assignment statement:
$SetResults = $SetCalc[$i];
It should instead use .= for concatenation. Here is how it should look:
if($CalcSets == 1){
for($i=0;$i<$CalcSets;$i++){
$SetResults .= $SetCalc[$i];
echo '<strong>'.(string)$SetResults.'</strong>';
}
DB_Insert($SetResults);
}
Hope it works!
I completely agree with the solution from #KemalFadillah for using the implode() method. From your code snippet, I understand that $calculations is the array that stores the main values, i.e. Array(1, 2, 3, 4, 5). So you can do:
$calculations = PerformCalc($min, $highest, $OperatorType);
$s = implode (', ', $calculations);
DB_Insert($s);
I hope that makes sense?
You are executing the last for loop only if $calcSets == 1 and have an $i<$calcSets condition
How about doing it like this
$SetCalc = "";
foreach ($calculations as $key => $DisplayCalcs) {
 echo $SetCalc .= $DisplayCalcs.', ';
}
DB_Insert("(".$SetCalc.")");
You're looking for the implode() function to format the numbers.
$formatted = implode(',', $calculations); // Produce 1,2,3,4,etc...
http://php.net/manual/en/function.implode.php

excluding previously randomized integer, and randomize again without it

<?php
if (isset($_POST['Roll!'])) {
$sides = $_POST['sides'];
$rolled = rand(1,$sides);
echo "$rolled was rolled by the dice, it is now out!";
}
?>
This is the code I currently have. After rolling that number, however, I want it to roll again, but without the previously rolled number, until it has rolled all number except one, which would be the winning number. I have no idea how to go about doing that. Any ideas?
EDIT: I'm sorry, I should have been more clear, thank you all for the help so far, but I also need to echo each number rolled, such as
echo "$rolledArray[0] was rolled, it lost.\n";
echo "$rolledArray[1] was rolled, it lost.\n";
echo "$rolledArray[2] was rolled, it lost.\n";
echo "$rolledArray[3] was rolled, it lost.\n";
echo "$rolledArray[x] was rolled, it lost.\n";
echo "$rolledArray[x] was rolled, it lost.\n";
echo "$rolledArray[50?] was rolled, it lost.";
EDIT AGAIN: Also I only want them to have to click Roll! once, not multiple times until they've rolled all the numbers, meaning no need for session, I think, though I could be wrong, most of you are clearly more experienced than me.
Sorry, I should have mentioned that before as well.
To answer your direct question:
You can put all of the possible numbers into an array, and get a random index for that array. Once you have an index, remove the item from the array and redo the random over the smaller array:
$possible = range(1, $_POST['sides']); // build the possible values
$rolledIndex = rand (0, count($possible)); // get a random index
$rolled = $possible[$rolledIndex]; // get the rolled number
unset($possible[$rolledIndex]); // and remove the rolled nuber
// now you can simply redo the random:
$rolledIndex = rand (0, count($possible)); // get a random index on the smaller array
$rolled = $possible[$rolledIndex]; // get the 2nd rolled number
However, If you want to have a random order on the dice throws, simply use this:
// generate an array with all values from 1 to the posted value (e.g. 1,2,3,4,5,6)
$possible = range(1, $_POST['sides']);
// this reorders the array by random (e.g. 4,3,1,5,2,6)
$throwOrder = $possible;
shuffle($throwOrder);
print_r($throwOrder);
Now you can simply iterate over the $throwOrder array and have a random order of dice throws:
Array (
0 => 4,
1 => 3,
2 => 1,
3 => 5,
4 => 2,
5 => 6
)
Edit To get the desired output from the second method, simply do this:
// get the last index of the array of thrown dices
$lastIndex = count($throwOrder)-1;
// iterate through the array, printing the results
foreach ($throwOrder as $key => $rolled) {
// check if the current key matches the last key in the array
if ($key != $lastIndex) {
// if not, the number has lost
echo $rolled, " was rolled, it lost.\n";
} else {
// we have reached the last element of the array
echo $rolled, " was the last, it won.\n";
}
}
I think you need to have array $thrownNumbers, which holds every number previously thrown. And every new throw (OMG... the word), you check if it's in array. If yes, throw again. Simplest possible solution.
Edit: As for keeping the array during moving to another page, you can use:
$_SESSION
cookies (hm)
have serialized array as hidden value in form
There.
You can throw it in the $_SESSION to keep track of it between posts/request or append it to the URL and pass it yourself each time as a URI param.
<?php
if(!isset($_SESSION['numbers']){
$_SESSION['numbers'] = range(1,6); //same as array(1,2,3,4,5,6)
}
$numbers = $_SESSION['numbers'];
if(count($numbers)>1){ //is more than one number left
$rand_index = array_rand($numbers); //choose a number from an array, returns the index
print('you rolled '.$numbers[$rand_index].' loser'); // tell them they lost
unset($numbers[$rand_index]); //remove that element from the array
$_SESSION['numbers'] = $numbers; //set new array back to session
}else{
print(array_pop($numbers).' is the winner!'); //pop the remaining number out of the array and print it with winner notification
}
?>
edit: updated to session usage
It is not a bad idea to add to the URL if you use properly. The good side is that you don't store data in the session, the bad side is that the request is bigger each time. To avoid tampering you can use:
$url = 'numbers.php?throwed='.implode(',',$throwed).'&sign='.sha1(serialize($throwed).'mysecretpassword');
And use this to get check:
$throwed = explode(',',$_GET['throwed']);
$not_tampered = sha1(serialize($throwed).'mysecretpassword') == $_GET['sign'];
Just create an array (or other type of list) of all possible numbers and randomly order it. Then, instead of picking a new number each time just advance through the array until you get to the last but one.
Alternatively, you could just go straight to the last number in the list and that's the winner.
It depends on the situation, but creating an array with all the possible numbers for all the visitors in your web can be a very bad idea, sessions files can grow unnecessarily.
If they are like numbers from 1 to 10 I think it would be OK, but if they are numbers from 1 to 1 million creating arrays with those ranges saved in the session is pretty much a bad idea.
I think it's better to save the rolled results and generate a new one until it doesn't exist in the array.

Categories