php range query - php

Basic question here. I am using php(smarty) range to populate an array for days in the month.
$smarty->assign('date', range(1,31 ));
The form sends OK, but because counts start at 0, when I pick 20 from dropdown 19 gets sent in the form.
How do I set it so it starts at 1?

The range() function does not allow you to specify the keys for the array. The simplest option would be to create your own array:
$range = array();
for ($i = 1; $i <= 31; $i++) {
$range[$i] = $i;
}
$smarty->assign('date', $range);

$days = array_combine(range(1,31),range(1,31));
Or, possibly more efficient, although it's a micro-optimalisation:
$range = range(1,31);
$days = array_combine($range,$range);

Related

compare driving distance from JSON array

I'm using googledistancematrix api for calculating distance from login user to all my fields of db. That's my controller code.
$field_list = Field::all();
for ($i=0; $i < count($field_list); $i++)
{
$destination = $field_list[$i]['latitude'] . "," . $field_list[$i]['longitude'];
$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$origin&destinations=$destination&mode=driving&sensor=false";
$json = file_get_contents($details);
$details = json_decode($json, TRUE);
if (count($details['destination_addresses']) > 0 )
{
$distance = $details['rows'][0]['elements'][0]['duration']['text'];
$field_list[$i]->distance = $distance;
}
}
By this i'm getting following response:
https://jsoneditoronline.org/?id=a35cedef327244ceb19ed35a2a4c8ddf
But i want to show only those fields whose distance < or = 30 mins.
Thanks
It's a simple matter to convert the time to seconds using strtotime() as follows:
$time=strtotime($details['rows'][0]['elements'][0]['duration']['text']);
if (($time-time()>1800) {
// ignore this element, probably in loop so do a continue
}
This is based on using your example line above which is only for a single element. You would need to wrap it with a loop and perform the calculation for each element.
You can use strtotime
$min = strtotime("30 mins");
$val = strtotime("0 hours 10 mins");
echo $min <= $val? "yes":"no";
(here if you want to test it)
in your case
if (count($details['destination_addresses']) > 0 ){
$min = strtotime("30 mins");
$distance = $details['rows'][0]['elements'][0]['duration']['text'];
if($min <= strtotime($distance)){
//do your logic
}
}

Create an array only knowing max and min values

Coding in PHP, I currently have an array of 100 values, which looks like this:
$cmassarray = array(630.00,629.70,629.40,629.10,628.80,628.50,628.20,627.90,627.60,627.30,627.00,
626.70,626.40,626.10,625.80,625.50,625.20,624.90,624.60,624.30,624.00,623.70,
623.40,623.10,622.80,622.50,622.20,621.90,621.60,621.30,621.00,620.70,620.40,
620.10,619.80,619.50,619.20,618.90,618.60,618.30,618.00,617.70,617.40,617.10,
616.80,616.50,616.20,615.90,615.60,615.30,615.00,614.70,614.40,614.10,613.80,
613.50,613.20,612.90,612.60,612.30,612.00,611.70,611.40,611.10,610.80,610.50,
610.20,609.90,609.60,609.30,609.00,608.70,608.40,608.10,607.80,607.50,607.20,
606.90,606.60,606.30,606.00,605.70,605.40,605.10,604.80,604.50,604.20,603.90,
603.60,603.30,603.00,602.70,602.40,602.10,601.80,601.50,601.20,600.90,600.60,
600.30,600.00);
All of the steps are the same length, and I may need to change them (and/or the max/min values) at a future stage, so I would like to find a way to avoid having to re-calculate them manually and type them each time.
If I know the maximum value is 630.00 and the minimum value is 600.00, and that I have 100 steps, would it be possible to create an array specifying that each value is an increment on this equation?
x (array value) = 600+((Max-Min)/100)*y)
where y is the incremental step in the scale.
Thank you for any help!
An alternative to using loops and all that would be range
$start=630;
$stop=600;
$steps=100;
$cmassarray=range( $start, $stop, ( ( $start-$stop ) / $steps ) );
You might want to have a look at the range function, which takes an optional third argument for step. This argument you can easily derive from your maximum, minimum and amount of steps. Here's an example:
$max = 630;
$min = 600;
$steps = 100;
$step = ($max - $min) / $steps;
$your_result = range( $max, $min, $step );
Start with this code:
$max = 630;
$min = 600;
$steps = 100;
$step = ($max - $min) / $steps;
$ar = [];
for ($i = $max; $i >= $min; $i -= $step) {
$ar[] = $i;
}

How to check matching array values in php?

Hi i have a repeating dates in array values i wan to count the number of repeating dates from the array value. I tried this but am not sure to do it correctly and am getting error Undefined offset: 0
<?php $array = array('2013-11-28','2013-11-28','2013-11-28','2013-11-29','2013-11-29','2013-11-30');
$len = sizeof($array);
$len = $len-1;
$day = array();
for($i=0; $i<=$len; $i++)
{
for($j=0; $j<=$len; $j++)
{
if($array[$i] == $array[$j])
{
if($day[0] == '')
{
$co = 1;
$day[] = $co;
}
else {
$day[$i] = $co++;
}
}
}
echo 'day'.$i.' '.$day[$i].' ';
}
?>
From the date values i should get 3 for 2013-11-28, 2 for 2013-11-29 and 1 for 2013-11-30 as you can see 2013-11-28 is presented 3 times , 2013-11-29 is presented 2 times and
2013-11-30 is presented one time.
I can understand that i am wrongly calculating because in the second loop i am again starting from first index so increasing the count.
I want to know the count of same dates. How to do this. Any other way to count this? Any help please?
Use array_count_values().
$dupesCount = array_count_values($array);
This will give you an array where the value is the key and the new value is the repetition count.

Fill in absent elements in an array

I have a code that generates total posts from a database per hour for the latest 10 hours. Now, the problem is that only hours with posts are displayed, but that won't work for me because i want to display the whole thing as a chart.
Example of the current array:
array("12"=>"20403",
"15"=>"17017",
"17"=>"84013");
The keys represent the hour in a 24 format. So what i need is a function that fills in the empty hours with 0 value.
Example:
$currenthour=date('H'); // i think it may be based on the latest hour.
array("11"="0",
"12"=>"20403",
"13"=>"0",
"14"=>"0",
"15"=>"17017",
"16"=>"0",
"17"=>"84013",
"18"=>"0",
"19"=>"0",
"20"=>"0");
Thanks!
foreach(range(0, 23) as $hour)
if(!isset($ary[$hour]))
$ary[$hour] = 0;
ksort($ary);
to fill in only last hours you may need something like
function last_hours($hour, $cnt) {
return $hour < $cnt - 1 ?
array_merge(range($hour, 0), range(23, 25 - $cnt + $hour)) :
range($hour, $hour - $cnt + 1);
}
and then
$now = date("G");
$new_array = array();
foreach(last_hours($now, 10) as $hour)
$new_array[$hour] = isset($ary[$hour]) ? $ary[$hour] : 0;
Use array_fill OR do it with a loop (assuming $hours is your array:
$currenthour=date('H');
for($i = $currenthour; $i < 23; $i++)
if(!isset($hours[$i]))
$hours[$i] = 0;
You can simply iterate through the array, and see if the value at the index is set. Like this:
Edit with your the last 10 hours:
$currenthour=date('H')
$beginrange = $currenthour - 10
if ($beginrange =< 0)
$beginrange = 23 + $beginrange
$endrange = $currenthour
//set up the for loop
foreach(range($beginrange, $endrange) as $i)
//check if the element is set
if(!isset($array[$i]))
// set it
$array[$i] = 0;

Calculate greatest number of days between two consecutive dates

If you have an array of ISO dates, how would you calculate the most days between two sequential dates from the array?
$array = array('2009-03-11', '2009-03-12', '2009-04-12', '2009-05-03', '2009-10-30');
I think I need a loop, some sort of iterating variable and a sort. I can't quite figure it out.
This is actually being output from MYSQL.
Here is how you can do it in PHP:
<?php
$array = array('2009-03-11', '2009-03-12', '2009-04-12', '2009-05-03', '2009-10-30');
# PHP was throwing errors until I set this
# it may be unnecessary depending on where you
# are using your code:
date_default_timezone_set("GMT");
$max = 0;
if( count($array) > 1 ){
for($i = 0; $i < count($array) - 1; $i++){
$start = strtotime( $array[$i] );
$end = strtotime( $array[$i + 1] );
$diff = $end - $start;
if($diff > $max) $max = $diff;
}
}
$max = $max / (60*60*24);
?>
It loops throw your items (it executes one less time than there are number of items) and compares each one. If the comparison is larger than the next, it updates max. Time is in seconds, so after the loop is over we convert the seconds into days.
This PHP script will give you the largest interval
1 ){
for($i = 0; $i $maxinterval) $maxinterval = $days;
}
}
?>
EDIT:
As [originally] worded the question can be understood in [at least ;-)] two ways:
A) The array contains a list of dates in ascending order. The task is to find the longuest period (expressed in number of days) between to consecutive dates in the array.
B) The array is not necessarily sorted. The task is to find the longuest period (expr. in number of days) between any two dates in the array
The following provides an answer to the "B" understanding of the question. For a response to "A", see dcneiner's solution
No Sorting needed!...
If it comes from MySQL, you may have this DBMS returns directly the MIN and MAX values for the considered list.
EDIT: As indicated by Darkerstar, the way the way the data is structured [and also the existing SQL query which returns the complete list as indicated in the question] generally dictate the way the query which produces the MIN and MAX value should be structured.
Maybe something like this:
SELECT MIN(the_date_field), MAX(the_date_field)
FROM the_table
WHERE -- whatever where conditions if any
--Note: no GROUP BY needed
If, somehow, you cannot use SQL, a single pass through the list will allow you to obtain the MIN and MAX value in the list (in O(n) time, that is).
Algorithm is trivial:
Set Min and Max Value to first item in [unsorted] list.
Iterate through each following item in the list, comparing it with the Min Value and replacing it if found smaller, and doing like-wise for the Max value...
With Min and Max values in hand, a simple difference gives the max number of days...
In PHP, it's looks like the following:
<?php
$array = array('2009-03-11', '2009-03-12', '2009-04-12', '2009-05-03', '2009-10-30');
# may need this as suggested by dcneiner
date_default_timezone_set("GMT");
$max = $array[0];
$min = $max;
for($i = 1; $i < count($array); $i++){
// Note that since the strings in the array are in the format YYYY-MM-DD,
// they can be compared as-is without requiring say strtotime conversion.
if ($array[$i] < $min)
$min = $array[$i];
if ($array[$i] > $max)
$max = $array[$i];
}
$day_count = (strtotime($max) - strtotime($min)) / (60*60*24);
?>

Categories