I am not great with arrays, but I have to build a new array from two arrays, the new array has to use the order of the first array but the data of the second but in the same order of the first.
The first array and order:
$forecastedMonths = array( "May 22", "Jun 22", "Jul 22", "Aug 22", "Sep 22", "Oct 22", "Nov 22", "Dec 22", "Jan 23", "Feb 23", "Mar 23", "Apr 23" );
And the second array I need to use the values of the second, but the keys in this represent the month.
Array ( [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 172427.89 //May [6] => 0 [7] => 243730.79 //Jul [8] => 0 [9] => 0 [10] => 0 [11] => 0 [12] => 0 )
So the desired outcome would be
Array ( [0] => 172427.89 [1] => 0 [2] => 243730.79 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 )
Advertisement
Answer
Use array_map()
to map the numeric data to the month-year expression. To relate the data’s numeric keys to the date expressions, use a datetime class plus a convert method, or just call date(strtotime())
.
Code: (Demo) (Classic loop)
var_export( array_map( fn($My) => $data[date('n', strtotime($My))], $forecastedMonths ) );
Very relevant page: In PHP given a month string such as “November” how can I return 11 without using a 12 part switch statement?