1

I've found this useful script to convert Google Spreadsheets into array. https://github.com/VernierSoftwareTechnology/google-spreadsheet-to-php-array/blob/master/google-spreadsheet-to-array.php

The resulting array is in the form:

Array
(
[1] => Array
    (
        [A] => id
        [B] => start_date
        [C] => title
        ...
[2] => Array
    (
        [A] => 10551920077
        [B] => 27/03/2014 19:00:00
        [C] => Up and Down The City Road
    )

and so on...

But I want the first row values to act as keys for the array, like:

Array
(
[2] => Array
    (
        [id] => 10551920077
        [start_date] => 27/03/2014 19:00:00
        [title] => Up and Down The City Road
    )

and so on...

I've tried to modify the code, but with no success. Any help?

Thanks in advance! :)

rjpedrosa
  • 652
  • 2
  • 7
  • 10

1 Answers1

1

Rather than modifying someone else's code (which is often very difficult), it's probably easier to change the data after the fact:

// get the column headers
$headers = $data[1];

// walk the array and change the keys
$data = array_map(function($row) use($headers) {
    // create an array to hold the new row
    $new = array();

    // step through the array keys...
    foreach(array_keys($row) as $k)
        // ...and add the new key to the new row with the old data
        $new[$headers[$k]] = $row[$k];

    // add the new row to the array
    return $new;
}, $data);

// now remove the header row from the data
unset($data[1]);

There's probably a way (using some combination of array_walk, array_map or other array functions) to replace that ugly foreach loop in there.

Kryten
  • 15,230
  • 6
  • 45
  • 68
  • Wow! It works like a charm! Hadn't tought about that approach. It completely makes sense! Thank you very much! :) – rjpedrosa Apr 11 '14 at 20:06