...

View Full Version : A little array help please (getting the right key value)



harbingerOTV
05-25-2011, 10:29 PM
function subval_sort($a,$subkey,$sort) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
$sort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}

$calendars = subval_sort($calendars,'realtime',asort);

foreach($calendars as $calendar1) {
foreach ($calendar1 as $key=>$calendar2) {
$todaysDate = date(strtotime($startTime));
if($key == 'realtime'){
// um...
}
}
}


my array looks like:



Array
(
[0] => Array
(
[title] => Event A
[when] => Fri May 27, 2011
[realtime] => 1306472400
[jstime] => May.27.2011
)

[1] => Array
(
[title] => Memorial Day
[when] => Mon May 30, 2011
[realtime] => 1306731600
[jstime] => May.30.2011
)

etc...


I;m using the 'realtime' in order to sort by date as $calendars is actually 5 arrays merged into one. The 'jstime' is the same date but formatted so I can apply my styling.

So what I need to do is get today's date (got it), then check all the items n the array that have the same time as today and echo out the 'title' from each array. That's this section:


foreach($calendars as $calendar1) {
foreach ($calendar1 as $key=>$calendar2) {
$todaysDate = date(strtotime($startTime));
if($key == 'realtime'){
// um...
}
}
}

a little lost as to what to write to grab each title in the array that has a 'realtime' of today.

Fou-Lu
05-25-2011, 11:52 PM
Write a filter for it, its way faster. Then you needn't worry about a conditional check.
Filter's have explicit signatures, so I'll be using a global variable for the realtime.



$realtime = 1306472400; // Calculate your day
function filterCalendarToday($value)
{
global $realtime;
$bResult = false;
if (isset($value['realtime']) && $value['realtime'] == $realtime)
{
$bResult = true;
}
return $bResult;
}

$calendars = // how you got your array
$aFilteredCalendars = array_filter($calendars, 'filterCalendarToday');
foreach ($aFilteredCalendars AS $value)
{
print $value['title'] . PHP_EOL;
}


How you get the $realtime is really up to you. You can drop the whole global by working explicitly on the time (strtotime with todays date puts it ad midnight), which can be a huge help. The $realtime is a convenience variable.

Inigoesdr
05-26-2011, 01:16 AM
If you know the name of the key you're looking for there is no need to loop a second time:

$todaysDate = strtotime($startTime);
foreach($calendars as $calendar)
{
if(isset($calendar['realtime']) && $calendar['realtime'] == $todaysDate)
{
echo $calendar['title'];
}
}
Unless I'm missing something.

harbingerOTV
05-26-2011, 03:02 PM
Spot on both of you. Inigoesdr's is easier to look at so I went that route as this will no doubt, fall into someone else hands someday. Easier to comment.

Once again it looks like I was close but, well, horseshoes and hand grenades ;)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum