Jump to content

get date from specific keys in associative array


russthebarber

Recommended Posts

I have an associative array with dates and prices:

$priceArr=array("2012-9-13"=>"34.00", "2012-9-14"=>"35.00", "2012-9-20"=>"36.00", "2012-10-21"=>"37.00", "2012-10-28"=>"38.00", "2012-10-29"=>"38.00");

I'm looking for the best solution. I need to loop through the array and explode just the keys that have a 9 in the middle (i.e. are in September). Then I just need the date value in a new array....which should look like this when finished:

$dateArr=array("13", "14", "20");

The exploding and pushing items into the second array I can do, it's just dealing with the key from the associative array that's new and confusing territory for me.

 

I'll try and explain it another way.  If you look at the keys (dates) in $priceArr, you'll see that there are three dates in September....the 13th, 14h and 20th. This information is in $dateArr.  The question is if $dateArr didn't exist how would I create it in php from $priceArr?

You can loop over the array's keys by using something like foreach(array_keys($priceArr) as $date), then inside the loop do whatever checking you need and build the date array. For example:

 

$dateArr = array();
foreach (array_keys($priceArr) as $date) {
    $datetime = new DateTime($date);
    if ($datetime->format('F') == 'September') {
        $dateArr[] = $datetime->format('j');
    }
}

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.