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'.
}
}
Related
I'm working on some stat tracking code for a game (yes, it's runescape. sue me).
I want to pull information from the high scores using an api which produces an array looking like this (captured using print_r)
Array
(
[getHiscore] => Array
(
[overall] => Array
(
[rank] => 61995
[lvl] => 2273
[totalxp] => 193310588
)
[attack] => Array
(
[rank] => 93406
[lvl] => 97
[totalxp] => 11747494
)
...and so on.
My question is how can i take what this api gives me and place it into a database table; I want to get an array such as this for a particular user and update their stats with it.
Would i use explode? It seems like the right idea to me but how would i actually use it to split the separate numbers and words?
My database is not totally realised yet, however each record will include a user name and then the level and total xp in each of 27 "skills". This almost certainly not best practice for database design but i'm as novice as they come so it's the best i can do.
You don't need to explode. It's an array and therefore it's already exploded. You need to iterate through it to build meaningful queries.
I'm not familiar with runescape so I don't know if your example is showing just the relevant fields of you need to discard some part. If it's the former, then you should try something like
$query="insert into stats_table (description, rank, lvl, totalexp) values (:description, :rank, :lvl, :totalext);";
$Statement = $DBConn->prepare($query);
foreach($fullArray as $description=>$subArray) {
$Statement->bindValue(':description',$description, PDO::PARAM_STR);
foreach($subArray as $key=>$value) {
$Statement->bindValue($key,$value, PDO::PARAM_STR);
}
$Statement->execute();
}
That will insert two rows containing
overall 61995 2273 193310588
attack 93406 97 11747494
PD: $DBConn is a PDO connection instance to whatever DB engine you're using.
Let's say this is all stored in the variable $ary:
$ary['getHiscore']['overall']['rank'] = 61995;
$ary['getHiscore']['overall']['lvl'] = 2273;
$ary['getHiscore']['overall']['totalxp'] = 193310588;
$ary['getHiscore']['attack']['rank'] = 93406;
$ary['getHiscore']['attack']['lvl'] = 97;
$ary['getHiscore']['attack']['totalxp'] = 11747494;
So, to get those values, it's:
$attackLevel = $ary['getHiscore']['attack']['lvl'];
If you
echo $attackLevel;
it would be 97.
Just pull the arrays out with a foreach loop and write some sql to insert the data. I don't know anything about your DB so if you want help there update your question please.
Simplest way to do this:
foreach($highscores as $highScoreType => $highScoreValues){
$rank = $highScoreValues['rank'];
$lvl = $highScoreValues['lvl'];
$totalXp = $highScoreValues['totalxp'];
//then it's up to you to put it into a table somehow.
}
$highScoreType will contain the values 'overall','attack',etc
This format of the foreach loop is extremely handy when iterating over an associative array (hash map/hash table, which is actually what all PHP arrays are underneath) will allow you to not only grab the value of the current pointed to entry, but also the key for that entry.
So, assume we have a single entry hashmap with key 'foo' and value 'bar'. If I want to show 'bar' I would simple
echo $map['foo'];//will output 'bar'
and if I put this into the above type of foreach loop
foreach($map as $fooKey => $barValue) {
echo $fooKey;//outputs 'foo'
echo $barValue;//outputs 'bar'
}
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 have this array:-
Array ( [0] => Prefectorial Board/Prefect/2011 [1] => Prefectorial Board/Head Prefect/2011 [2] => Class Positions/Head Prefect/2011 [3] => Prefectorial Board/Head Prefect/2011 )
How to detect this array have duplicate value and I want the participant to re-fill in his data.
I have try to use this method to detect:-
$max = max(array_values($lr_str));
$keys = array_keys($lr_str, $max);
but it seem like not work for me.
any idea on this?
thanks for advance.
I do not know if I understand you correctly, but you can test the array has duplicated values by using this:
if (count($your_array) === count(array_unique($your_array)) {
// array has no duplicated values
} else {
// array has duplicated values - see compared arrays
}
Are you looking for array_unique?
You can use array_unique() to remove duplicate values. If no values were removed then the returned array should have the same number of items as the original:
if(count($lr_str) == count(array_unique($lr_str))){
//tell participant to re=fill their data
}
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.
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.