[Solved] How to add missing keys to array


function getAllYears(array $array): array
{
    $allKeys = [];
    foreach ($array as $data) {
        foreach ($data['data'] as $years) {
            if (!in_array($years['x'], $allKeys, true)) {
                $allKeys[] = $years['x'];
            }
        }
    }
    sort($allKeys);
    return $allKeys;
}

function addMissingKeys(array $array): array
{
    $allYears = getAllYears($array);
    foreach ($array as $key => $data) {
        $currentYears = array_map(static function ($year) {
            return $year['x'];
        }, $data['data']);
        $yearToAdd = array_diff($allYears, $currentYears);
        foreach ($yearToAdd as $year) {
            $array[$key]['data'][] = [
                'x' => $year,
                'y' => 0,
            ];
        }
    }
    return $array;
}

$array = [
    [
        "name" => "7:00 AM",
        "data" => [
            [
                "x" => "2019",
                "y" => 1
            ]
        ]
    ],
    [
        "name" => "8:00 AM",
        "data" => [
            [
                "x" => "2019",
                "y" => 69
            ],
            [
                "x" => "2020",
                "y" => 4
            ],
            [
                "x" => "2021",
                "y" => 221
            ]
        ]
    ],
    [
        "name" => "9:00 AM",
        "data" => [
            [
                "x" => "2019",
                "y" => 6
            ],
            [
                "x" => "2020",
                "y" => 2
            ]
        ]
    ]
];

$array = addMissingKeys($array);

var_dump($array);

You can see result of this code here: https://sandbox.onlinephpfunctions.com/code/2c58df4749126199bf21357d1c615634a0ebd629

1

solved How to add missing keys to array