为每个 ACF 转发器字段行保存值并将所有值放入一个数组中 (PHP)

Save value for each ACF repeater field row and place all values into one array (PHP)

我正在使用 WordPress 和高级自定义字段来构建网站。

我的网站上有一个事件列表的高级自定义字段转发器字段。对于每个事件行,都有一个用于输入日期的子字段。

我试图将这些子字段保存到 $dates 数组中。但是,这个 $dates 数组输出的几个数组只有一个值 var_dump().

$dates 的输出:

array(1) { [0]=> string(20) "June 5, 2018 5:00 pm" }
array(1) { [0]=> string(22) "June 15, 2018 12:00 am" }
array(1) { [0]=> string(22) "July 13, 2018 12:00 am" }
array(1) { [0]=> string(22) "July 13, 2018 12:00 am" }
array(1) { [0]=> string(22) "July 27, 2018 12:00 am" }
array(1) { [0]=> string(24) "August 18, 2018 12:00 am" }

使用下面的代码,我尝试遍历 $dates 数组并将值转换为输出月份名称的 $month 变量。从日期到月份名称的转换工作正常,但我需要将每个转发器行的这些 $month 值放入一个 $months 数组中。

我尝试在下面创建一个 $months 数组并将每个 $month 值添加到该数组。此代码为每个转发器行输出单独的数组,数组中只有一个月份值。 (与 $dates 数组的问题相同。)

我不确定如何完成这个或者我是否以错误的方式看待这个问题。任何帮助将不胜感激!

<?php if (have_rows('events')):

while (have_rows('events')) : the_row();

$dates = array();
$dates[] = get_sub_field('date_time');

foreach ($dates as $date) {
  $timestamp = strtotime($date);
  $month = date('F', $timestamp);
  /* this code below does not work as intended */
  $months = array();
  $months[] = $month;
}

?>

您要在每个循环中重置月份数组。只需将分配移动到 while 循环之外。

$months = array();

while (have_rows('events')) : the_row();

    foreach ($dates as $date) {
        $timestamp = strtotime($date);
        $month = date('F', $timestamp);
        $months[] = $month;
    }

endwhile;