1
votes

I am using a PHP Google sheets client:

https://github.com/asimlqt/php-google-spreadsheet-client

This client implements v3 of the API:

https://developers.google.com/google-apps/spreadsheets/data

I usually get rows like this:

// simplified code:
$worksheet = $worksheetFeed->getByTitle($worksheet_id);
$listFeed = $worksheet->getListFeed();


foreach ($listFeed->getEntries() as $entry)
{
    $rows []= $entry->getValues();
}

Google turns "Admin Title" into the array key "admintitle". I would like to get a map of the Google array keys to the original Titles. For example, I want an array with entries like:

[admintitle] => "Admin Title"

etc.

How do I do that?

1

1 Answers

0
votes

I don't think there is anything in the API to do this, so I made my own function. Note that we are using the API client v2.3

function get_worksheet_column_titles($worksheet)
{
    $map = array();
    $already_in_map = array();

    $row_one_query = array(
        'min-row' => 1,
        'max-row' => 1
        );

    $cellfeed = $worksheet->getCellFeed($row_one_query);
    $entries = $cellfeed->getEntries();

    foreach ($entries as $cell)
    {
        $title = trim($cell->getContent());


        if ($title && $title[0] != '_')
        {
            $array_key = strtolower(preg_replace('/[^A-Z0-9_-]/i', '', $title));

            if ($already_in_map[$array_key])
            {
                // if identical column titles, google adds count to end

                $seq = 2;

                while ($already_in_map[$array_key.'_'.$seq])
                {
                    $seq++;
                }


                $array_key .= "_{$seq}";
            }

            // mark this key as used as used.
            $already_in_map[$array_key] = true;

            $map[$array_key] = $title;
        }
        else
        {
            continue;
        }
    }
    return $map;
}