Creating a different array related to different times a loop happens php - php

there. I'm having a problem with creating arrays in certain conditions in php, i'll try to explain. Here's my code:
for ($i = 1; $i < $tamanho_array_afundamento; $i++) {
if ($array_afundamento[$i] - $array_afundamento[$i - 1] > 1) {
$a = $array_afundamento[$i - 1];
$con->query('CREATE TABLE IF NOT EXISTS afunda_$a
SELECT (L1_forma_tensao_max + L1_forma_tensao_min)/2 as L1_forma_tensao, (L2_forma_tensao_max + L2_forma_tensao_min)/2 as L2_forma_tensao, (L3_forma_tensao_max + L3_forma_tensao_min)/2 as L3_forma_tensao
FROM afundamento
WHERE id > $prevNum AND id < $a');
$tabelas_intervalos_afunda1 = ($con->query("SELECT * FROM afunda_$a");
while ($row = $tabelas_intervalos_afunda->fetch(PDO::FETCH_ASSOC)) {
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}
$prevNum = $a;
}
}
So as u can see, i have an if statement in a for loop, what i'm wishing to do is to create
one set of:
{
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}
every time the if statement is runned. I was trying replacing this in the original code:
{
$array_forma_onda_fase1_afund_$a[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_$a[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_$a[] = $row['L3_forma_tensao'];
}
so as $a is changed everytime the if statement is accessed, i could have a different set of these arrays for everytime the if statement is accessed, but php doesn't accept this and i wouldn't have a very good result, though if i can reach it i would be pleased.
But my goal is to get:
{
$array_forma_onda_fase1_afund_1[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_1[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_1[] = $row['L3_forma_tensao'];
}
{
$array_forma_onda_fase1_afund_2[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund_2[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund_2[] = $row['L3_forma_tensao'];
}
...
where the last number represents the array retrieved for the n-th time the if statement runned. Does someone have a tip for it?
Thanks in advance! Would appreciate any help.
EDIT
As asked, my real world terms is as follows:
I have a table from which i need to take all the data that is inside a given interval. BUT, there's a problem, my data is a sine function whose amplitude may change indefinite times (the data bank is entered by the user) and, when the amplitude goes inside that interval, i need to make some operations like getting the least value achieved while the data was inside that interval and some other parameters, for each interval separately, (That's why i created all those tables.) and count how many times it happpened.
So, in order to make one of the operations, i need an array with the data for each time the databank entered by the user goes in that interval (given by the limits of the create query.).
If i were not clear, just tell me please!
EDIT 2
Here's the image of part of the table i'm working with:
http://postimg.org/image/5vegnk043/
so, when the sine gets inside the interval i need, it can be seen by the L1_RMS column, who accuses it, so it's when i need to get the interval data until it gets outside the interval. But it may happens as many times as this table entered by the user brings it on and we need to bear in mind that i need all the intervals separately to deal with the data of each one.

Physics uh?
You can do what you wanted with the arrays, it's not pretty, but it's possible.
You can dynamically name your arrays with the _$a in the end, Variables variables, such as:
${"array_forma_onda_fase3_afund_" . $a}[] = "fisica é medo";

Related

Small scope/huge frustration mystery: buggy array behavior in php

So crazy! I have a bug that's 100% reproducible, it happens in only a few lines of code, yet I cannot for the life of me determine what the problem is.
My project is a workout maker, and the mystery involves two functions:
get_pairings: It makes a set of $together_pairs (easy) and $mixed_pairs (annoying), and combines them into $all_pairs, used to make the workout.
make_mixed_pairs: this has different logic depending on whether it's a partner vs solo workout. Both cases return a set of $mixed_pairs (in the same exact format), called by the function above.
The symptoms/clues:
The case of the solo workout is fine, $all_pairs will only contain $mixed_pairs (because as it's defined, $together_pairs are only for partner workouts)
In the case of the a partner workout, when I combine the two sets in get_pairings(), $all_pairs only successfully gets the first set I give it! (If I swap those lines at step 2 and add $together_pairs first, $all_pairs contains only those. If I do $mixed_pairs first, $all_pairs contains only that).
Then if I uncomment that second-to-last line in make_mixed_pairs() just for troubleshooting to see what happens, then $all_pairs does successfully include exercises from both sets!
That suggests the problem is something I'm doing wrong in making the arrays in make_mixed_pairs(), but I confirmed that the resulting format is identical in both cases.
Anyone see what else I could be missing? I've been narrowing down this bug for 4 hours so far- I can't make it any smaller, and I can't see what's wrong :(
Update: I updated the for loop in make_mixed_pairs() to stop at $mixed_pair_count - 1 (instead of just $mixed_pair_count), and now I sometimes get one single 'together_pair' mixed in the $all_pairs results; the same damn one each time, weirdly. Though it's not 'fixed', because again when I change the order that I add the two sets in get_pairings, when I add $together_pairs first, then $all_pairs is ENTIRELY those- it's so strange...
Here are the functions: first get_pairings (relevant part is right before and after step 2):
/**
* Used in make_workout.php: take the user's available resources, and return valid exercises
*/
function get_pairings($exercises, $count, $outdoor_partner_workout)
{
// 1. Prep our variables, and put exercises into the appropriate buckets
$mixed_exercises = array();
$together_pairs = array();
$mixed_pairs = array();
$all_pairs = array();
$selected_pairs = array();
// Sort the valid exercises: self_pairing exercises go as they are, with extra
// array for consistent formatting. Mixed ones go into $mixed_exercises array
// for more specialized pairing in make_mixed_pairs
foreach($exercises as $exercise)
{
if ($exercise['self_pairing'])
{
$pair = array($exercise);
array_push($together_pairs, [$pair]);
}
else
{
$this_exercise = array($exercise);
array_push($mixed_exercises, $this_exercise);
}
}
// Now get the mixed_pairs
$mixed_pairs = make_mixed_pairs($mixed_exercises, $outdoor_partner_workout);
// 2. combine together into one set, and select random pairs for the workout
// Add both sets to the array of all pairs (to pick from afterward)
$all_pairs += $mixed_pairs;
$all_pairs += $together_pairs;
// Now let's choose at random our desired # of pairs, and save them in $selected_pairs
$pairing_keys = array_rand($all_pairs, $count);
foreach($pairing_keys as $key)
{
array_push($selected_pairs, $all_pairs[$key]);
}
// Finally, shuffle it so we don't always see the self-pairs first
shuffle($selected_pairs);
return $selected_pairs;
}
And the other one- make_mixed_pairs: there are two cases, the first is complicated (and shows the bug) and the second is simple (and works):
/**
* Used by get_pairings: in case of a partner workout that has open space (where
* one person can travel to a point while the other does an exercise til they return)
* we'll pair exercises in a special way. (If not, fine to grab random pairs)
*/
function make_mixed_pairs($mixed_exercises, $outdoor_partner_workout)
{
$mixed_pairs = array();
// When it's an outdoor partner workout, we want to pair travelling with stationary
// put them into arrays and then we'll make pairs using one from each
if ($outdoor_partner_workout)
{
$mixed_travelling = array();
$mixed_stationary = array();
foreach($mixed_exercises as $exercise)
{
if ($exercise[0]['travelling'])
{
array_push($mixed_travelling, $exercise);
}
else
{
array_push($mixed_stationary, $exercise);
}
}
shuffle($mixed_travelling);
shuffle($mixed_stationary);
// determine the smaller set, and pair exercises that many times
$mixed_pair_count = min(count($mixed_travelling), count($mixed_stationary));
for ($i=0; $i < $mixed_pair_count; $i++)
{
$this_pair = array($mixed_travelling[$i], $mixed_stationary[$i]);
array_push($mixed_pairs, $this_pair); // problem is adding them here- we get only self_pairs
}
}
// Otherwise we can just grab pairs from mixed_exercises
else
{
// shuffle the array so it's in random order, then chunk it into pairs
shuffle($mixed_exercises);
$mixed_pairs = array_chunk($mixed_exercises, 2);
}
// $mixed_pairs = array_chunk($mixed_exercises, 2); // when I replace it with this, it works
return $mixed_pairs;
}
Oh for Pete's sake: I mentioned this to a friend, who told me that union is flukey in php, and that I should use array_merge instead.
I replaced these lines:
$all_pairs += $together_pairs;
$all_pairs += $mixed_pairs;
with this:
$all_pairs = array_merge($together_pairs, $mixed_pairs);
And now it all works

Only saving the last entry

I have a form to edit the entrys in the database. With this the staff from my site can change every entry of an movie. It works percetly expect one little thing: It's also possible to change every episode title by iteselfs, and because every movie can have other count of episode, the php has to handle with it. It's working but not the way I want, my code I'm using only take the last entry and save it to the first episode from the movie.
Here is my code.
for ($e = 0; $e < count($_POST["episode"]); $e++) {
$con->query("UPDATE anime_episode SET ep_title = '".$_POST['episode']."' WHERE ep_nr = $e AND ani_id = $a");
}
There can only be one $_POST["episode"]. PHP will group all of the entries into that one variable so count will always return 1. You should try parsing $_POST["episode"] into an array or something first and then counting those elements.

PHP array comparison with different lengths

I need to compare values from 2 arrays that are not always the same size, each containing either a login or a logout time. I need to get the time difference total or time logged in between these values. Where I am getting caught is the logout result is usually smaller then the login. I tried the following but it isn't accurate at all.
$offset = 0;
for($i=0;$i<sizeof($login_ary);$i++){
//unset($time_logged);
$time_logged = Array();
while( (int)$login_ary[$i] > (int)$logout_ary[$i] ) {
$offset++;
}
$time_logged['login'] = $login_ary[$i] + $offset;
$time_logged['logout'] = $logout_ary[$i];
$calc_ary[] = $time_logged;
}
$time_logged_in = "undefined";
End result I need to get either an array with lined up login/logoffs or a calculation of the total time difference between the login time and then logout time. But I have to exclude logins that don't have an associated logout.
EDITS
1) Times inside of the arrays are unix timestamps
2) the arrays aren't static as this is done inside a loop for each user in a result set so the var_dump would look something like the following
login_arr
Array([0] => '1385402632',[1] => '1385763384',[2] => '1387293992')
logout_arr
Array([0] => '1387294012')
** MY SOLUTION **
My solution is out of context of the original question which is why I posted it as an edit instead of an answer. But here is what I did, the simplicity of it makes me feel foolish that I didn't think of it originally. What I did, is write the session timeout into the logout_ary since the data was going to be unrepresented otherwise, we decided that fudging a time was better then completely avoiding it. So I took the login time and fudged a logout time and spliced it into the array at the same point. I still would like to know the true answer to this problem if there is one though.
for($i=0;$i<sizeof($login_ary);$i++){
//unset($time_logged);
$time_logged = Array();
if( (int)$login_ary[$i] > (int)$logout_ary[$i] ) {
array_splice($logout_ary,$i,0,$login_ary[$i]+$session_length);
$time_logged['login'] = $login_ary[$i];
$time_logged['logout'] = $logout_ary[$i];
} else {
$time_logged['login'] = $login_ary[$i];
$time_logged['logout'] = $logout_ary[$i];
}
$calc_ary[] = $time_logged;
}
Just read the comments, I think this might be what you're after comment and I can see if I can help more.
<?php
function calcTime($login_ary, $loutout_ary) {
$login_ary_length = sizeof($login_ary);
$logout_ary_length = sizeof($logout_ary);
if($login_ary_length != $logout_ary_length) {
$diff = $login_ary_length - $logout_ary_length;
//just find the code that suits your format and put it in the function strtotime()
$timestamp = strtotime('TODAYS DATE AND TIME');
//for the amount of diff we add todays date and time to the array so that they are eqal
for(i=0; i<=$diff; i++) {
array_push($logout_ary, $timestamp);
}
//I'm going to leave this for you to do.
return $total_hours;
}
}
?>
I hope this is what you're looking for.
What exactly is stored in the two arrays? Just time variables? How are you to know if say that login_ary[i] is the login time for the log_out[i] time? Also, why not just take the log_out time - the log_in time to get the time differential?

Running a form with incomplete/empty values

I'm writing a script that calculates the total distance, in miles, traveled on a trip. It needs to calculate the total distance, and the distance between any midpoints. Right now it calculates the total distance fine. I am using drop-boxes, and have allowed to it accept up to 5 midpoints. Now, I may just be trying to make this more complicated than it needs to be but...
I'd like to be able to run the script even if three of the midpoint forms are left empty (which would just say "Select City" with a value of " " or null). Is there a way I can have the script run when the three fields of the form are left empty??
EDIT: Each 'index' or 'pont' is defined with a = " ";. I'm using a multidimentional array for the whole script and the 7 drop boxes start with a selected value of "Select City" which has an empty/null value. I just want to know how to run the form/script when two of the mid-point values/drop boxes are left with the initial value of "Select City".
Sorry, here is some of my code:
<?php
if (isset($_POST['Submit'])) {
$StartIndex = stripslashes($_POST['Start']);
$EndIndex = stripslashes($_POST['End']);
if (isset($Distances[$StartIndex][$EndIndex]))
echo "Total trip distance from $StartIndex to $EndIndex is". $Distances[$StartIndex][$EndIndex]." miles<br/>";
else
echo "Distance could not be calculated";
}
?>
This is where I'm stopped at...
<?php
if (isset($_POST['Submit'])) {
$Point1 = stripslashes($_POST['1']);
?>
^^the other four midpoints are the same, I have zero clue how to still run the form when only the start city, end city, and two mid-point cities are selected. I'd add the whole script but it very long with the multidimensional array
To see what my form looks like you can go to >> 131.118.95.215/users/mjswiontek0/project/city/citytocity.php
Just evaluate your test (e.g. empty($_POST["1"])) on every midpoint to find, if you want to include it into calculation.
See commented (very generic) example:
if (isset($_POST['Submit']))
{
// start with the start index
$PrevIndex = stripslashes($_POST['Start']);
$Point = 1;
$Distance = 0;
do
{
// do we have the N-th midpoint?
$HavePoint = !empty($_POST[$Point]);
// if not, use end point
$NextIndex = stripslashes($_POST[$HavePoint ? $Point : 'End']);
// add distance between the two midpoint to total
$Distance += $Distances[$PrevIndex][$NextIndex];
// make current point the previous point to the next iteration
$PrevIndex = $NextIndex;
// move to the next point for the next iteration
$Point++;
}
while ($HavePoint);
}

Finding first possibility

If I have this pattern to build ID's:
CX00 where the 0's are replaceable with just a number.. but the following is already in use:
- CX00
- CX02
- CX04
- CX05
- CX07
- CX10
- CX11
- CX12
How can I easily find, either via PHP or MySQL the values CX01, CX03, CX06, CX08, CX09, CX13+ as available values?
I don't know how your data is stored, so I'll leave getting the IDs in an array. Once you do, this will find the next available one.
<?php
function make_id($n) {
$out = 'CX';
if ($n < 10) $out .= '0';
return $out . $n;
}
// Get these from some source
$items = array('CX00', 'CX02', 'CX04', 'CX05');
$id = make_id(0);
for($i=0; in_array($id, $items); $i++)
$id = make_id($i);
echo $id;
?>
This is called a brute-force method, and if you have a lot of IDs there are probably more efficient ways. With 100 maximum, there shouldn't be any problems.
In php simply count up through the ids using a for loop until you have found enough of the unused ids... how many total ids do you expect to have?

Categories