Search code examples
phparraysmultidimensional-arrayarray-combinecsv-header

Use first row of a 2d array as the new keys of each subsequent row


I'm looking for a solution to create an array of associative arrays from an array of indexed array where the first row should be used as the keys for all subsequent rows.

What I have is a csv/xls file that has header values on the first row and data in all remaining rows.

Row1: header Row2,3,4,5: data

the array looks:

[
    [
        "country",
        "state",
        "city",
        "name",
        "address",
        "gender",
        "status"
    ],
    [
        "Argentina",
        "Corrientes",
        "Corrientes",
        "Jorge",
        "Avenida Avellaneda 12",
        "Masculino",
        "Activo"
    ],
    [
        "Argentina",
        "Chaco",
        "Resistencia",
        "Mariano",
        "Avenida Peron 12",
        "Masculino",
        "Activo"
    ]
]

The result i need to get at the end is:

[
    [
        'country' => 'Argentina',
        'state' => 'Corrientes',
        'city' => 'Corrientes',
        'name' => 'Jorge',
        'address' => 'Avenida Avellaneda 12',
        'gender' => 'Masculino',
        'status' => 'Activo',
    ],
    [
        'country' => 'Argentina',
        'state' => 'Chaco',
        'city' => 'Resistencia',
        'name' => 'Mariano',
        'address' => 'Avenida Peron 12',
        'gender' => 'Masculino',
        'status' => 'Activo',
    ]
]

Solution

  • $array = $your_flat_array;
    
    for ($i = 1; $i < count($array); $i++) {
    
        $new_array[$i-1] = [];
    
        foreach ($array[$i] as $key => $value) {
    
            $new_array[$i-1][$array[0][$key]] = $value;
        }
    }
    
    print_r($new_array);