【问题标题】:Google Spreadsheet to PHP script modification谷歌电子表格到 PHP 脚本修改
【发布时间】:2014-04-11 19:22:59
【问题描述】:

我发现这个有用的脚本可以将 Google 电子表格转换为数组。 https://github.com/VernierSoftwareTechnology/google-spreadsheet-to-php-array/blob/master/google-spreadsheet-to-array.php

结果数组的格式为:

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...

但我希望第一行值充当数组的键,例如:

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

and so on...

我尝试修改代码,但没有成功。 有什么帮助吗?

提前致谢! :)

【问题讨论】:

    标签: php arrays google-apps-script spreadsheet


    【解决方案1】:

    比起修改别人的代码(这通常很困难),事后更改数据可能更容易:

    // 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]);
    

    可能有一种方法(使用array_walkarray_map 或其他数组函数的某种组合)来替换其中丑陋的foreach 循环。

    【讨论】:

    • 哇!它就像一个魅力!对这种方法没有强硬。这完全有道理!非常感谢你! :)
    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多