How to convert a one-dimensional array multidimensional?

There is an array of the form:

array(
 [0] => 04.02.2013-03.03.2013
 [1] => 04.03.2013-03.04.2013
 [2] => 04.12.2013-03.01.2014
 [3] => 04.01.2014-03.02.2014
 [4] => 04.12.2014-03.01.2015
 [5] => 04.01.2015-03.02.2015
 [6] => 04.02.2015-03.03.2015
);

how(and whether) to make an array of the form:
array(
 [2013] => array(
 [0] => 04.02-03.03,
 [1] => 04.03-03.04,
 [2] => 04.12-03.01
),
 [2014] => array(
 [0] => 04.01-03.02,
 [1] => 04.12-03.01
),
 [2014] => array(
 [0] => 04.01-03.02,
 [1] => 04.02-03.03
),
 );
June 5th 19 at 21:20
4 answers
June 5th 19 at 21:22
Solution
can, normal bust, parsim string on two dates, select the year, make array key
June 5th 19 at 21:24
Solution
$result = [];
foreach ($sourceArray as $key=>$value) {
 $dates = explode('-', $value);
 $numbers = explode('.', $dates[0]);
 $year = $numbers[2];
 if (!isset($result[$year])) {
 $result[$year] = [];
}
 $result[$year][] = substr($dates[0], 0, 5) . '-' . substr($dates[0], 0, 5);
}


Demo sandbox.onlinephpfunctions.com/code/5102f544f69cf6...
without explode to do. - florencio.Zemlak60 commented on June 5th 19 at 21:27
June 5th 19 at 21:26
Solution
but why?
in this place, through the years, you have
[2014] => array(
....
[1] => 04.12(.2014)-03.01(.2015) - florencio.Zemlak60 commented on June 5th 19 at 21:29
so intended) - florencio.Zemlak60 commented on June 5th 19 at 21:32
like why? It happens that the date range falls beginning in one year and end in another. There are already business logic will depend on felts poke into both felts for the first year. - katlynn_Gre commented on June 5th 19 at 21:35
but this loss of information... bad business logic. not necessarily because there is a difference in year. - Henderson_Beat commented on June 5th 19 at 21:38
June 5th 19 at 21:28
Solution
$array1 = [
 '04.02.2013-03.03.2013', 
'04.03.2013-03.04.2013',
'04.12.2013-03.01.2014',
'04.01.2014-03.02.2014',
'04.12.2014-03.01.2015',
'04.01.2015-03.02.2015',
'04.02.2015-03.03.2015',
];

$result = [];

foreach ($arr as $r) {
 $year = [];
 if (preg_match('/.[0-9]{4}/', $r, $year)) {
 $year = $year[0];
 if (!isset($result[$year]) {
 $result[$year] = [];
}
 $result[$year][] = str_replace(".$year", ", $r);
}
}
foreach ($arr as $r) {
 $year = [];
 preg_match_all('/^(.{5})\.(.{4})-(.{5})\.(.{4})$/', $r, $year);
 isset($result[$year[2][0]]) || $result[$year[2][0]] = [];
$result[$year[2][0]][]="{$year[1][0]}-{$year[3][0]}";
}
- florencio.Zemlak60 commented on June 5th 19 at 21:31

Find more questions by tags PHP