I would like to know if there is any way to change or update a multidimensional array from this
Array ( [AZ] => Array ( [1] => 2020-01 [2] => 2020-02 ) [BY] => Array ( [0] => 2020-03 [1] => 2020-04 ) [CX] => Array ( [1] => 2020-05 [2] => 2020-06 [3] => 2020-07 ) [DW] => Array ( [106] => 2019-01 [107] => 2019-02 [108] => 2019-03) )
To this
Array ( [AZ] => Array ( [1] => 2020 [2] => 2020 ) [BY] => Array ( [0] => 2020 [1] => 2020 ) [CX] => Array ( [1] => 2020 [2] => 2020 [3] => 2020 ) [DW] => Array ( [106] => 2019 [107] => 2019 [108] => 2019) )
I don’t know if this is possible but I hope someone can help me
Advertisement
Answer
You can use array_walk_recursive
to walk over all the values in the array, changing those that match a YYYY-MM
format to YYYY
using preg_replace
:
array_walk_recursive($array, function (&$v) { $v = preg_replace('/^(d{4})-dd$/', '$1', $v); });
Note we use &$v
as the argument to the callback so that we can change the values in the array.
Output:
Array ( [AZ] => Array ( [1] => 2020 [2] => 2020 ) [BY] => Array ( [0] => 2020 [1] => 2020 ) [CX] => Array ( [1] => 2020 [2] => 2020 [3] => 2020 ) [DW] => Array ( [106] => 2019 [107] => 2019 [108] => 2019 ) )