Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅返回php数组中与我的自定义字段月份相等的项(数组\过滤器)_Php_Arrays_Filter_Array Filter - Fatal编程技术网

仅返回php数组中与我的自定义字段月份相等的项(数组\过滤器)

仅返回php数组中与我的自定义字段月份相等的项(数组\过滤器),php,arrays,filter,array-filter,Php,Arrays,Filter,Array Filter,我返回了本月和下个月的所有周五的下拉列表,效果很好 我还有一个额外的步骤,我只想在下拉列表中显示与此字段中月份相等的月份:$productMonth=get_字段(“product_month”) 该字段返回以下值:“May” 因此,我需要查看该数组中的所有项,并且仅当它们关联的月份与$productMonth匹配时才返回它们 我尝试过使用array_filter,但我知道$var.date('F')不是答案,我想我可能可以通过检索字符串的最后一位来做一些事情,因为这将始终返回月份,但这并不理想

我返回了本月和下个月的所有周五的下拉列表,效果很好

我还有一个额外的步骤,我只想在下拉列表中显示与此字段中月份相等的月份:$productMonth=get_字段(“product_month”)

该字段返回以下值:“May”

因此,我需要查看该数组中的所有项,并且仅当它们关联的月份与$productMonth匹配时才返回它们

我尝试过使用array_filter,但我知道$var.date('F')不是答案,我想我可能可以通过检索字符串的最后一位来做一些事情,因为这将始终返回月份,但这并不理想:

$array2 = array_filter($fridaysUnique, "matches_month");

function matches_month($var, $productMonth)
{
    return ($var.date('F') === $productMonth);
}
下面是我剩下的代码:

<?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>

我们将非常感谢您的帮助,并欢迎您提出任何使代码更整洁的建议


谢谢

如果将数组过滤器更改为以下值,则过滤器方法将为您提供所需的值:

$array2 = array_filter($fridaysUnique, function ($val) use ($productMonth) {
    return (DateTime::createFromFormat('l jS F', $val))->format('F') === $productMonth);
});
上面的代码所做的是遍历
$fridaysUnique
数组中的所有值,并将每个值转换为
DateTime
对象,该对象被格式化为字符串,以便与
$productMonth
中的值进行比较(注意,
use
的使用允许您在匿名筛选方法中使用
$productMonth
变量)


但是,与其像这样将日期转换两次,我建议您首先在数组中存储
DateTime
对象。

您应该将时间戳值存储到数组中,而不是存储格式化的日期。然后,您可以在筛选函数中轻松地格式化时间戳,例如,仅以书面形式获取月份表单。要使其以所需格式显示,应在实际创建输出时进行处理。@CBroe非常感谢您,这将更加整洁