【问题标题】:Combining 2 array in a foreach loop在foreach循环中组合2个数组
【发布时间】:2017-02-07 23:34:15
【问题描述】:
$user = $this->get_user_or_redirect();
        $calendars = $user->get_calendars1();
        $events = [];
        foreach ($calendars as $calendar) 
        {
            $events += $calendar->get_events();

        }

$calendars 是一个数组,其中包含特定用户的所有日历。 每个日历都有许多事件。函数get_event()为每个日历返回一个事件数组。

我想要做的是将事件数组(特定于日历)附加到特定于用户的空事件数组 ($events = [])。 我使用了调试器,似乎foreach循环中的代码不起作用,但我不知道为什么。

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    如下更改循环以将数据附加到数组。

    foreach ($calendars as $calendar) 
    {
          $events[] = $calendar->get_events();
    
    }
    

    【讨论】:

      【解决方案2】:

      您应该使用 [] 为每个 $calendar 添加一个 $event 实例

      $user = $this->get_user_or_redirect();
          $calendars = $user->get_calendars1();
          $events = [];
          foreach ($calendars as $calendar) 
          {
              $events[] = $calendar->get_events();
      
          }
      

      【讨论】:

        【解决方案3】:

        更换

        $events += $calendar->get_events();
        

        $events[] = $calendar->get_events();
        

        工作。

        【讨论】:

          【解决方案4】:

          您希望使用

          保存事件数组
          1. 特定于日历
          2. 特定于用户

          你需要像这样创建一个多维数组。

          foreach ($calendars as $calendar) 
          {
              $events[$user][$calendar][] = $calendar->get_events();
          
          }
          

          通过这种方式,您将能够跟踪您想要的事件。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-12-19
            • 1970-01-01
            相关资源
            最近更新 更多