I need help, badly. What I am making right now is a date picker. Pretty much updating on it for my own use.
I needed to block out specific date ranges. I found a code to do this, and it utilizes arrays. I like that.
What I then needed was a way to create the array with every date within the range, because I only entered the Start Date and the End Date. Found one. Works like a charm.
But now, I have a problem. It creates a new array using the same $. So the only array that the calender registers is the newest one. Essentially, what I need is just 1 array.
I've tried a few things, but nothing seems to work. Been thinking about this for a while now. Any help?
function createDateRangeArray($strDateFrom,$strDateTo) //Changes a Range of Dates to Specific Dates
{
$aryRange = array(); //Creates an Array
$iDateFrom = mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo = mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo >= $iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom += 86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange; //Returns to step 1 and adds another value into the array
}
$d = "SELECT startdate, enddate FROM classdetails";
$f = mysql_query($d);
while ($e = mysql_fetch_array($f))
{
while (list($g, $h) = each($e)) { $$g = $h; }
{
$aryDates = createDateRangeArray($startdate,$enddate);
print_r($aryDates);
echo "<br />";
}
}
And for those wondering, I do include references of where some of my work is taken from, even if heavily modified.
As you can see, the problem lies with the fact that once it creates an array, it just creates a new one. I've tried using ifelse statements, empty(), isset(), increments (didn't even know how to use them, just thought a long time and deleted it).
So, what can I do here?
What I always get back is (I only have 2 rows of dummy data):
Array ( [0] => 2010-12-16 [1] => 2010-12-17 [2] => 2010-12-18 [3] => 2010-12-19 [4] => 2010-12-20 [5] => 2010-12-21 [6] => 2010-12-22 [7] => 2010-12-23 )
Array ( [0] => 2010-12-25 [1] => 2010-12-26 [2] => 2010-12-27 [3] => 2010-12-28 [4] => 2010-12-29 )
The problem lies with the loop itself. The first instance does what it is tole to do. The second instance onwards, $aryDates just gets replaced.
Any help would be greatly appreciated.
while (list($g, $h) = each($e)) { $$g = $h; }
Oh good god. Do NOT use variable variables. Especially when you've got a perfectly good array being generated by the mysql fetch call as is. THis is why you're having trouble debugging your code.
You could rewrite the while loop like this
while ($e = mysql_fetch_array($f)) {
$aryDates = createDateRangeArray($e['startdate'],$e['enddate']);
print_r($aryDates);
echo "<br />";
}
Far more readable, far easier to follow what's happening, and absolutely NO NEED WHATSOEVER for variable variables.
You penance is 500 lashes with a wet noodle while repeating the following mantra: "I shall not use variable variables"
Beyond that, of course it's creating a new array each time, you're telling it to at the top of your createDateRange function:
$aryRange = array(); //Creates an Array
If you want to reuse the same array over multiple function calls, make it a static variable:
static $aryRange = array();
which will preserve it across successive calls, which would then let you append each calls's dates.
Related
I am trying to merge two parts of a code. To do that i have to store the echo'd array column output from a function which i call on
multiple times into an array or arrays on which I can perform computations.
Here's what i'm trying to do:
<?php
$searchquery[1] ="jupiter";
$searchquery[2] ="venus";
//can be multiple queries
include ('find.php');
for($i=0;$i<count($searchquery);$i++)
{
find($searchquery[$i]);
}
/find.php echoes back to me a MySQL query which then
creates a 2 dimensional array for me called
/$searchresult which looks like this as an example
t x (let's call first column t for example, and second x)
|1|3|
|1|4|
|2|6|
|4|8|
|7|1|
and it echoes it back to me, this works.
But, i need to use the first column (t) (11247) output from find.php
which was the result of the searchquery "jupiter",
and i need to store it as some sort of array in this current sheet,
theni need to store the "venus" searchquery which is let's say
t x
|1|3|
|2|4|
|3|4|
|4|6|
|5|4|
and store the first column (t) as an array in this current sheet.
I am trying to store the echos from the find.php function as arrays so that
i can perform the following operation in the current sheet:
$venusarrayt = array(1, 1, 2, 4, 7); //the manually defined
//$searchresult first column output from find.php which echos to me (t) (11247)
$jupiterarrayt = array(1, 2, 3,4,5); //the manually defined
//$searchresult first column output from find.php which echos to me (t) (12345)
//I need to perform the following operation and sum all of the t combinations
for($l=0;$l<count($venusarrayt);$l++){
for($s=0;$s<count($jupiterarrayt);$s++){
echo $venusarrayt[$l]+$jupiterarrayt[$s];
This part works! But i am having trouble though merging the echo'd $searchresult output into an array on which i can perform the above
for loops. In this example i am doing it by hand by typing into the php sheet "venusarrayt and jupiterarrayt".
I am sure there is some way to store echo'd array column results from a function which i call upon multiple times into an array, but i
haven't figured out yet how. Please help.
I hope this helps:
<?php
$searchquery[0] ="jupiter";
$searchquery[1] ="venus";
//can be multiple queries
include ('find.php');
$results=null;
for($i=0;$i<count($searchquery);$i++)
{
$temp=find($searchquery[$i]);
$results[$i]=$temp[t];
}
for($l=0;$l<count($results[1]);$l++){
for($s=0;$s<count($results[0]);$s++){
echo $results[1][$l]+$results[0][$s];
}
}
Clear solution for anyway of further working with your searched data can looks something like this:
$searchquery[1] ="jupiter";
$searchquery[2] ="venus";
$search_result = array(); $i=0;
foreach($searchquery as $current_query){
$current_result = FindResul($current_query);
// FindResult will be your function which process single query and returns result of it
$search_result[$i]['query'] = $current_query;
$search_result[$i]['result'] = $current_result;
$i++;
}
After the execution the code above you will have array 2-lvl array with clear and easy to work with structure. You can use it how you'd like to compare data or show it in the way you want.
Resulting array will have such structure:
$search_result[0]['query'] = 'jupiter';
$search_result[0]['result'] = '...jupiter resul';
$search_result[1]['query'] = 'venus';
$search_result[1]['result'] = '...venus result';
You have to create nested array to resolve the issue I would give a little example how to do?
$searchquery[1] ="jupiter";
$searchquery[2] ="venus";
for($i=1;$i<=count($searchquery);$i++){
$temp=find($searchquery[$i]);
$results[$i]=$temp[t];
}
$k=$i;
for($z=0;$z<=$i;$z++){
$total='';
for($p=0;$p<=$k;$p++){
$total=$total+$results[$p][$z];
}
echo $total;
echo "\n";
}
function find($word){
return array('t' => array('1', '2', '4', '7'));
}
and answer would be something like this:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 7
)
[2] => Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 7
)
)
2
4
8
14
This solution will add all the n number of queries first result, second result and so on.......
I am looping between 2 times in 10 minute intervals, which works fine and outputs a time like so:
<?=$time->format('H:i')?>
I then am pulling data from the database of times I then want to see if the data in the loop matches whats coming out of the database. I have created a method to get me all the records from the database and outputs them into an array. I then wanted to use in_array to match them up then run the value through another method to get data about it. Problem is that it doesnt match up, problem being:
if (array_search($time->format('H:i'), $bookings))
echo "Match";
$booking is a multi-dimension array looking like:
Array (
[0] => Array ( [id] => 1 [time] => 12:00 )
[1] => Array ( [id] => 2 [time] => 15:00 )
...
)
Thanks in advance!
It would be much easier if you get the values directly from database. still if you want to process it in php, you can try with array_walk(). I am not sure about the syntax but should be something like
function search($value, $key, $needle)
{
array_search($needle, $value);
}
array_walk($bookings, 'search', $time->format('H:i'));
where $value will be your inner arrays.
Guys, please correct me if i am wrong with the syntax
It would probably be simpler to directly query the database accordingly - if you can - and than your query would be something like
select * from `table_name` WHERE `date_field` = $your_date
If that does not form a solution you can use array_walk as above or simply loop a little more:
foreach($bookings as $array) {
if(array_search($time->format('H:i'), $array)) {
echo 'match';
// If you don't want to keep searching use 'break'.
}
}
Is it possible to store PHP syntax in variables for later use and repetition like this:
$ifStart = "if(";
$ifEnd = "){ echo 'Test'; }";
$ifStart 'A' == 'B' $ifEnd;
Edit: What I'm trying to accomplish is this:
I have 3 form fields, and when the PHP script is loaded, any of the three can be set. None can be set, two, one... So I need some way to determine how many are set and what to output according to that. That's why.
Edit: Right, so I have one HTML Select and two text input fields. My script checks if those fields are set (isset) and does some code accordingly, putting information into arrays etc. What I want to do now though, is to check if the variables have been set one by one, so I can output the correct results which I have stored in arrays.
New edit: This is obviously so hard to explain. But imagine a search engine where you decide which fields you'd like to fill out and then the script checks which fields are set and loops through the array with all the results, only gathering out the elements with sub-elements corresponding to the requested search, that's what I'm trying to achieve.
Here's the array design with AGE and COUNTY selected/set in the POST (hence why there's no [city] elements:
Array
(
[1] => Array
(
[id] => 1
[age] => 19
[county] => 4353
)
[2] => Array
(
[id] => 2
[age] => 20
[county] => 4020
)
[3] => Array
(
[id] => 3
[age] => 30
[county] => 4020
)
)
Still trying to figure out how to only select out a specific array element depending on -its- contents. For example, I have an array like this:
Array ( 1: [age][county], 2: [age][county], 3: [age], 4: [county], 5: [age][county] )
I'd then like to only select the IDs containing both age and county, in this example ID 1, 2 and 5.
Edit: It'll be similar to a SQL query: WHERE age AND county, only this is in an array
It is possible...
BUT
if you have to do it, there's definitely something wrong with your design!
[Edit after your edit]
Your edit shows me that I was right. What you're trying to do, can be accomplished in a better way!
So if I understand you correctly, you want to alter your output according to which form fields have been filled/answered by the user. So far you are storing some values from the $_POST array in another array. In order to generate your output, it would be best to loop over that array and concatenate strings, depending on what has been filled.
foreach ($myArray as $formField => $value)
{
//do something for each $formField, depending on the $value
}
If that still leaves you puzzled, comment here.
The way you wrote it, it would not work, you would need to use eval(). The use of eval() , is in most cases bad practice. That would not be the main problem though, the main problem is, that such code is hard to read, hard to debug as well as maintain and hard to document. All it all, it is bad practice and will lead to a bad solution and more problems.
One clean way (clean because it avoids eval()) to do relatively dynamic code would be to store either a function name or, after php 5.3, a function reference.
E.g. something like:
$callback = "truth_check";
$condition_result = ($a == $b);
if(is_callable($callback)){
$callback($condition_result);
}
See a running example here: http://ideone.com/1SBYS
In your case the callback could be a result to run, e.g. "print_message_on_true_input" as some comparison function and the input could be the result of a conditional tested anywhere in your code, e.g. $print = (false || $a == $b);
Give your specific use cases, though, because 90% of the time intended behavior can be acheived much less fragily without resorting to any dynamic code at all.
Is it possible? Yes, using eval.
Should you do it? NO NO NO NO PLEASE DON'T.
No. You can use functions instead.
function my_compare($a, $b, $symbol = '==') {
eval('$result = $a ' . $symbol . ' $b;');
if ($result) echo 'Test';
}
// ...
my_compare('A', 'B');
Keep in mind the comments above that warn you about this idea!
But you could probably do this:
$ifStart = "if(";
$ifEnd = "){ echo 'Test'; }";
eval( " {$ifStart} 'A' == 'B' {$ifEnd} " );
Ok, so what you need has little relation to the dynamic code involved in your original question, so I'm going to start over and propose a different approach entirely:
//INITIALIZE
//get your input variables, defaulting to null
$inputs = array('select'=>#$_REQUEST['select_name'], 'input1'=>#$_REQUEST['input_1_name'], 'input2'=>#$_REQUEST['input_2_name']);
// initialize your output variables
$out1 = $out2 = $out3 = null;
//MANIPULATIONS
//perform actions based on the presence of variables in the array
if($inputs['select'] == 'whatever'){
$out1 = 'select was '.htmlentities($inputs['select']);
}
// .... perform more manipulations, setting output strings ...
// OUTPUT SECTION
echo $out1.$out2.$out3;
I am checking a list of 10 spots, each spot w/ 3 top users to see if a user is in an array before echoing and storing.
foreach($top_10['top_10'] as $top10) //loop each spot
{
$getuser = ltrim($top10['url'], " users/" ); //strip url
if ($usercount < 3) {
if ((array_search($getuser, $array) !== true)) {
echo $getuser;
$array[$c++] = $getuser;
}
else {
echo "duplicate <br /><br />";
}
}
}
The problem I am having is that for every loop, it creates a multi-dimensional array for some reason which only allows array_search to search the current array and not all combined. I am wanting to store everything in the same $array. This is what I see after a print_r($array)
Array ( [0] => 120728 [1] => 205247 ) Array ( [0] => 232123 [1] => 091928 )
There seems to be more to this code. As there are variables being called in it that aren't defined, such as $c, $usercount, etc.. And using array_search with the 2nd parameter of $array if it doesn't exist is not a good idea also. Since it seems like $array is being set within the if statement for this only.
And you don't seem to be using the $top10 value within the foreach loop at all..., why is this?
It would help to see more of the code for me to be able to help you.
Explanation
I have a multidimensional array that is iterated over to created a categorized view of people with different research interests. The main array look something like this:
Array
(
...
['Cell Biology'] => Array(4 elements)
['Molecular'] => Array(6 elements)
['Biology Education'] => Array(14 elements)
['Plant Biology'] => Array(19 elements) <--- Last element in array
)
I know that the entire array is intact and correctly structured. The only information that is inside these array is an user id, like so:
Array ('Plant Biology') 19 elements
(
[0] => 737
[1] => 742
[2] => 748
...
)
My problem is that after i run the main array through a foreach loop the last 'sub-array' gets messed up. By messed up I mean that what you see about instead look like:
String (13 characters) 'Plant Biology'
This is without doing at all anything inside the loop with to the array that gets corrupted.
Any tips to what it might be?
PHP Code
// ---> Array is OK here
echo "<h2>Research divided</h2>";
// Loop areas and list them in 2 columns
foreach($research['areas'] as $area => $areaArray) {
// ---> Here it is already corrupted
$count = count($areaArray);
if($count > 0) {
echo "<h3>$area</h3><hr/>";
echo "<ul>";
// Loop users within areas, divided up in 2 columns
for($i=0 ; $i<$count ; $i++) {
$uid = $areaArray[$i];
echo "<li>$uid</li>";
}
echo "</ul>";
}
}
Are $area or $areaArray being used in different function elsewhere in your script? Wht happens if you rename them to $loop_area and $loop_areaArray to prevent accidental overwriting of variables?
It looks like an error that can occur if you loop over the array previously by referance using the same variable name for the value.
So if earlier in your code $areaArray is used in a foreach by referance it might corrupt your data.
Make sure both variables in your foreach are not used previously or unset them before the loop.
Check out:
http://bugs.php.net/29992
For more info on this kind of problem.