【问题标题】:Foreach loop returning only last resultForeach 循环仅返回最后一个结果
【发布时间】:2020-05-06 00:50:27
【问题描述】:

我需要格式化 YYYY-MM-DD 日期以输出如“2020 年 1 月 12 日”,我已经得到正确输出的日期,但代码只会输出我想要的五个值之一,我已经显然错过了什么。

我遇到了以下代码仅输出单个结果的问题:

function populate_dropdown($form){

    //Reading posts for "Events" post type;
    $posts = get_posts("post_type=el_events&orderby=date&order=asc&el_eventcategory=flo-talanoa&numberposts=-1");

    //Creating drop down item array.
    $items = array();
    //Adding post dates titles to the items array
    foreach($posts as $post)
        $unformatteddate = $post->startdate;
        $dateTime = DateTime::createFromFormat("Y-m-d", $unformatteddate);
        $dateformatted = $dateTime->format('j F Y');
        $items[] = array(
            "value" =>  $dateformatted . ': ' . $post->location, 
            "text" => $dateformatted . ': ' . $post->location
        );

    //Adding items to field id 1.
    foreach($form["fields"] as &$field)
        if($field["id"] == 1){
            $field["type"] = "select";
            $field["choices"] = $items;
        }

    return $form;
}

如果我替换:

            $unformatteddate = $post->startdate;
            $dateTime = DateTime::createFromFormat("Y-m-d", $unformatteddate);
            $dateformatted = $dateTime->format('j F Y');
            $items[] = array(
                "value" =>  $dateformatted . ': ' . $post->location, 
                "text" => $dateformatted . ': ' . $post->location
            );

与:

$items[] = array("value" => $post->startdate . ': ' . $post->location, "text" => $post->startdate . ': ' . $post->location);

代码输出所有五个值(尽管使用 YYYY-MM-DD 日期格式),我缺少什么?我是 PHP 新手。

提前致谢

【问题讨论】:

    标签: php wordpress foreach


    【解决方案1】:

    您在 foreach 中缺少花括号 {}。

    【讨论】:

      【解决方案2】:

      您忘记在 foreach 循环中添加 {}

      foreach($posts as $post){
          $unformatteddate = $post->startdate;
          $dateTime = DateTime::createFromFormat("Y-m-d", $unformatteddate);
          $dateformatted = $dateTime->format('j F Y');
          $items[] = array(
              "value" =>  $dateformatted . ': ' . $post->location, 
              "text" => $dateformatted . ': ' . $post->location
          );
      }
      
      //Adding items to field id 1.
      foreach($form["fields"] as &$field){
          if($field["id"] == 1){
              $field["type"] = "select";
              $field["choices"] = $items;
          }
      }
      

      【讨论】:

      • 谢谢!我就知道会是那样的蠢事,我一直盯着它看了一天,不敢相信它这么简单......
      猜你喜欢
      • 2014-10-26
      • 2018-06-05
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 2021-09-24
      • 2017-03-10
      • 1970-01-01
      相关资源
      最近更新 更多