Search code examples
phparraysdefault-value

Push elements into array where a month is missing


I want to fill missing months in an array with zeros.

Input Data:

$d = [
        [
          'type' =>  25500,
          'month' => 'July'
         ],
         [
          'type' => 5465,
          'month' => 'January'
         ],
         [
          'type' => 40000,
          'month' => 'April'
         ],
         [
          'type' => 35000,
          'month' => 'June'
         ],
         [
          'type' => 10000,
          'month' => 'February'
     ]
 ];

$allmonths = ['January','February','March', 'April','May','June','July','August','September','October','November','December'];

My Code:

$res = [];
foreach ($allmonths  as $key => $mes) {
    $teste = array_search($mes, array_column($d, 'month'));
    if ($teste) {
        $res[$teste] = ['type' => 2, 'moth '=> $mes];
    } else {
        $res[] = ['type' => 0,'moth '=> $mes];
    }
}

I have been trying to solve this problem but with no success.

Expected Result:

Array
(
    [0] => Array
        (
            [type] => 25500
            [month] => July
        )
    [1] => Array
        (
            [type] => 5465
            [month] => January
        )
    [2] => Array
        (
            [type] => 40000
            [month] => April
        )
    [3] => Array
        (
            [type] => 35000
            [month] => June
        )
    [4] => Array
        (
            [type] => 10000
            [month] => February
        )
    [5] => Array
        (
            [type] => 0
            [month] => March
        )
    [6] => Array
        (
            [type] => 0
            [month] => May
        )
    [7] => Array
        (
            [type] => 0
            [month] => August
        )
    [8] => Array
        (
            [type] => 0
            [month] => September
        )
    [9] => Array
        (
            [type] => 0
            [month] => October
        )
    [10] => Array
        (
            [type] => 0
            [month] => November
        )
    [11] => Array
        (
            [type] => 0
            [month] => December
        )
)

Solution

  • I will go with array_column(), array_diff() and a single foreach()

    Process:

    1)Create an array of all months

    2)Get all month present in your array using array_column().

    3)Find the not available months in your array using array_diff().

    4)Iterate over this difference and add them to your current array.

    $allMonths = ['January','February','March', 'April','May','June','July','August','September','October','November','December'];
    
    $currentMonths = array_column($d, 'month');
    
    $notIncludedMonth = array_diff($allMonths,$currentMonths);
    
    foreach ($notIncludedMonth as $month) {
        $d[] = [
            'type' => 0,
            'month' => $month,
        ];
    }
    
    print_r($d);
    

    Output : https://3v4l.org/GsFoO