Joshua Lutz
Joshua Lutz

Reputation: 13

Convert Indexed Multidimensional Array to Associative Array using first element as key

I am pulling my hair out trying to get an indexed multidimensional array in PHP converted to an associative array using the first element of the indexed array as the keys for the associative array. Not sure I explained this correctly so see the example below.

Here is a snippet of the array, the actual one has 48 elements in the second dimension, I just put 3 as an example.

[0] => Array
    (
        [0] => fsn
        [1] => ac_type
        [2] => flt_type
    )

[1] => Array
    (
        [0] => 1219601
        [1] => 748
        [2] => SS
    )
[2] => Array
    (
        [0] => 1206869
        [1] => 748
        [2] => SS
    )

What I'm wanting is:

[0] => Array
    (
        [fsn] => 1219601
        [ac_type] => 748
        [flt_type] => SS
    )
[1] => Array
    (
        [fsn] => 1206869
        [ac_type] => 748
        [flt_type] => SS
    )

Here is what I'm working with so far, I am using PHPSpreadsheet to pull the info from an XLS file into an array. The end goal is to push the data to a mysql database.

<?php
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
$worksheet = $spreadsheet->getActiveSheet();
$rows = [];
foreach ($worksheet->getRowIterator() AS $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
    $cells = [];
    foreach ($cellIterator as $cell) {
        $cells[] = $cell->getValue();
    }
    $rows[] = $cells;
}

echo '<pre>';
print_r ($rows);
echo '</pre>';
?>

Any help would be greatly appreciated!!

Upvotes: 1

Views: 1483

Answers (1)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

Shift off the first item to get the keys:

$keys = array_shift($array);

Then map array_combine over the rest of it using the array of keys.

$result = array_map(function($values) use ($keys) {
    return array_combine($keys, $values); }, $array);

Based on the code shown in your edit, it looks like you could actually do this as you build the array instead if you replace $rows[] = $cells; with:

if (isset($keys)) {
    $rows[] = array_combine($keys, $cells);
} else {
    $keys = $cells;
}

Upvotes: 6

Related Questions