Reputation: 227
I am returning all of the Fridays for the current month and next month in a dropdown, which works fine.
I have an additional step where I want to only show the months in that dropdown that equal to the month in this field: $productMonth = get_field('product_month');
That field returns the following value: "May".
So I need to look at all items in that array and only return them if the month they have associated to them matches $productMonth.
I have tried using array_filter but I know $var.date('F') isn't the answer, I assume I could probably do something by retrieving the last bit of the string as that would always return the month, but that's not ideal:
$array2 = array_filter($fridaysUnique, "matches_month");
function matches_month($var, $productMonth)
{
return ($var.date('F') === $productMonth);
}
And here is the rest of my code:
<?php
$productMonth = get_field('product_month');
$thisMonth = date('F');
$nextMonth = date('F', strtotime("next month"));
$fridays = array();
$fridays[0] = date('l jS F', strtotime('first friday of this month'));
$fridays[1] = date('l jS F', strtotime('second friday of this month'));
$fridays[2] = date('l jS F', strtotime('third friday of this month'));
$fridays[3] = date('l jS F', strtotime('fourth friday of this month'));
$fridays[4] = date('l jS F', strtotime('fifth friday of this month'));
$fridays[5] = date('l jS F', strtotime('first friday of next month'));
$fridays[6] = date('l jS F', strtotime('second friday of next month'));
$fridays[7] = date('l jS F', strtotime('third friday of next month'));
$fridays[8] = date('l jS F', strtotime('fourth friday of next month'));
$fridays[9] = date('l jS F', strtotime('fifth friday of next month'));
$fridaysUnique = array_unique($fridays);
?>
<select>
<?php foreach ( $fridaysUnique as $friday ) : ?>
<option value=""><?php echo $friday; ?></option>
<?php endforeach; ?>
</select>
Help would be greatly appreciated and any recommendations on making the code neater are welcomed.
Thanks
Upvotes: 1
Views: 181
Reputation: 593
If you change your array_filter to the following the filter method will give you the values you want:
$array2 = array_filter($fridaysUnique, function ($val) use ($productMonth) {
return (DateTime::createFromFormat('l jS F', $val))->format('F') === $productMonth);
});
What the code above does is it runs through all the values in your $fridaysUnique
array and converts each value to a DateTime
object that is formatted to a string for comparison with the value in $productMonth
(note the use of use
allowing you to use the $productMonth
variable inside your anonymous filtering method).
However instead of converting dates twice like this I would suggest you store DateTime
objects in your array to start with.
Upvotes: 1