phparraysmultidimensional-arraymerging-data

How to remove first dimension of an array without loosing keys?


How can I reduce my multidimensional array without losing the associative keys?

I have an array that has multiple arrays inside - the first associative key is a date value and the second associative key is an hour value.

$array = [
    [
        '2022-05-10' => [9 => [1, 2]]
    ],
    [
        '2022-05-10' => [9 => [3, 4]]
    ],
    [
        '2022-05-10' => [10 => [5, 6]]
    ],
    [
        '2022-05-11' => [9 => [7, 8]]
    ]
];

Desired result:

[
   '2022-05-10' => [
       9 => [1, 2, 3, 4],
       10 => [5, 6]
   ],
   '2022-05-11' => [
       9 => [7, 8]
   ]
]

I tried array_merge_recursive() but it destroys my integer hour keys and re-indexes the elements.


Solution

  • okay found a solution on: PHP : multidimensional array merge recursive

    function array_merge_recursive_ex(array $array1, array $array2)
    {
        $merged = $array1;
    
        foreach ($array2 as $key => & $value) {
            if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
                $merged[$key] = array_merge_recursive_ex($merged[$key], $value);
            } else if (is_numeric($key)) {
                 if (!in_array($value, $merged)) {
                    $merged[] = $value;
                 }
            } else {
                $merged[$key] = $value;
            }
        }
    
        return $merged;
    }
    

    and with this function i can merge that mutlidemensional array without loosing keys:

    $newarray =[];
    foreach($array as $firstkey){
        $newarray = array_merge_recursive_ex($newarray, $firstkey);
    }