简体   繁体   中英

Combining 2 array in a foreach loop

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

        }

$calendars is an array containing all the calendars for a specific user. Each calendar has a number of events. The function get_event() returns an array of events for each calendar.

What I want to do is append the array of events (specific to a calendar) to an empty array of events ( $events = [] ) specific to the user. I used the debugger and it seems that the code in the foreach loop doesn't work but I have no idea why.

change your loop as following to append data to array.

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

}

You should use [] for add a $event instance for each $calendar

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

    }

Replacing

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

by

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

worked.

You want an events array to be saved with

  1. specific to a calendar
  2. specific to the user

you need to create a multidimensional array like this.

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

}

In this way you will be able to track the event you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM