loops - Create multiple phases in Stripe instead of schedule using PHP foreach

I have this piece of PHP code that iterates through a Stripe request to create schedules. In the request below it is iterating through the entire request (thereby creating a new subscription for each element of the array). What I need it to do is to only iterate it through the phases part (so that all of the payment dates are in one schedule).

$paymentdates = array ("1592043010", "1592910720", "1594850400",  "1595851200", "1597021320");

  foreach ($paymentdates as $paymentdate) {
  $schedule = \Stripe\SubscriptionSchedule::create([
    'customer' => 'cus_HMDwmb8iAV0X7k',
    'start_date' => 'now',
    'end_behavior' => 'cancel',

      'phases' => [
        // only iterate this part
        [
          'end_date' => $paymentdate,
          'proration_behavior' => 'none',
          'plans' => [
            [
              'price_data' => [
                'unit_amount' => 2300,
                'currency' => 'usd',
                'product' => 'prod_HMDoA6Jpf0U1Fh',
                'recurring' => [
                    'interval' => 'year',
                ],
              ],
            ],
          ],
          // end iterate here
        ],
      ],
  ]);

  }

Answer

Solution:

What you should do here is build the array of phases first and at the end create the schedule. I don't fully grasp why you have so many phases with the same plan but ultimately you'd want something like this

$paymentdates = array ("1592043010", "1592910720", "1594850400",  "1595851200", "1597021320");
$phases = []
foreach ($paymentdates as $paymentdate) {
  $phases[] = [
    'end_date' => $paymentdate,
    'plans' => [
        [
          'price_data' => [
            'unit_amount' => 2300,
            'currency' => 'usd',
            'product' => 'prod_HMDoA6Jpf0U1Fh',
            'recurring' => [
                'interval' => 'year',
            ],
          ],
        ],
      ],
  ];
}
$schedule = \Stripe\SubscriptionSchedule::create([
  'customer' => 'cus_HMDwmb8iAV0X7k',
  'start_date' => 'now',
  'end_behavior' => 'cancel',
  'phases' => $phases
]);

Source