phparraysmultidimensional-arrayflatten

Flatten a 2d array while preserving associative row keys


I need to flatten a 2d array to become a 1d array without losing the 2nd level keys in the process.

Sample data:

$data = [
    [2015 => '2015'],
    [2016 => '2016'],
    [2017 => '2017'],
    [2018 => '2018'],
    [2019 => '2019'],
    [2020 => '2020'],
    [2021 => '2021'],
    [2022 => '2022'],
    [2023 => '2023']
];

Desired output:

[
    2015 => '2015',
    2016 => '2016',
    2017 => '2017',
    2018 => '2018',
    2019 => '2019',
    2020 => '2020',
    2021 => '2021',
    2022 => '2022',
    2023 => '2023'
]

Is it possible to get output like this?


Solution

  • You could do simple foreach loop:

    <?php
    
    $years = array(
        array(2015 => '2015'),
        array(2016 => '2016'),
        array(2017 => '2017'),
        array(2018 => '2018'),
        array(2019 => '2019'),
        array(2020 => '2020'),
        array(2021 => '2021'),
        array(2022 => '2022'),
        array(2023 => '2023')
    );
    
    foreach($years as $year) {
        $key = key($year);
        $value = current($year);
        $result[$key] = $value;
    }
    
    var_dump($result);
    

    Output:

    $result = [
        2015 => '2015',
        2016 => '2016',
        2017 => '2017',
        2018 => '2018',
        2019 => '2019',
        2020 => '2020',
        2021 => '2021',
        2022 => '2022',
        2023 => '2023'
    ];