Ron Brouwers Ron Brouwers - 8 months ago 24
PHP Question

PHP create multiple arrays for each of the value passed in a foreach

Check out my code snippet below.

$data = [];

foreach($dates as $date)
{
for ($x = 0; $x <= $this->days; $x++)
{
$data[] = clone $date;

$date = $date->subDays('1');
}
}


$dates
is an array consisting of an x amount of carbon instances. For each of the dates, I want to create a new set of dates, using the above code snippet.

$this->days
can be any number. If it's set to 1, I will create one addtional date as opposed to the one I already have. Example:

I have two dates:

2016-01-10 // 10th of january 2016
2016-05-15 // 15th of may 2016


Using the above code snippet, I will create an additional
$date
for each of my
$dates
in my array, by subtracting one day from it and adding it to the array. So afterwards, I will have an array consisting of four dates:

$data = ['2016-01-10', '2016-01-09', '2016-05-15', '2016-05-14']; // Example array, not the actual output


It works as expected. But what I want, is for each of the dates, to be put in a new object, or array, instead of having them all in one single array. So for the
january
dates in my example, I want an array, or object, and also for the
may
dates.

Any ideas of how I could accomplish this?

Answer

Here is a way to create the sub-arrays:

$data = [];

foreach($dates as $date)
{
    $partition = []; // create new sub-array
    for ($x = 0; $x <= $this->days; $x++)
    {
        $partition[] = clone $date; // add to it

        $date = $date->subDays('1');
    }
    $data[] = $partition; // now add to main array
}