首页 > 解决方案 > 通过PHP在google sheet api中添加数组表单数据

问题描述

我在 PHP 中使用 google sheet API 在 google 电子表格中添加我的 html 表单数据。所有其他数据都已附加到工作表的相应单元格中,因为每个值都有一个数据,除了一个数据是数组中的一个数据,因为 html 输入数据位于多个复选框中。

我的谷歌表格:

在此处输入图像描述

我在 php 中的代码:

<?php

//add data to google spreadsheet
require __DIR__ . '/vendor/autoload.php';

//getting form data
    $name_kanji = $_POST['name_kanji'];
    $name_katakana = $_POST['name_katakana'];
    $age = $_POST['age'];
    $phone = $_POST['phone'];
    $userEmail = $_POST['email'];
    $zip_code = $_POST['zip_code'];
    $city = $_POST['city'];
    $address1 = $_POST['address1'];
    $address2 = $_POST['address2'];
    $experience = $_POST['experience'];
    $others_text = $_POST['others_text'];
    $lessons = $_POST['check_list'];
    $source = $_POST['source'];

//Reading data from spreadsheet.

$client = new \Google_Client();

$client->setApplicationName('Google Sheets and PHP');

$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);

$client->setAccessType('offline');

$client->setAuthConfig(__DIR__ . '/credentials.json');

$service = new Google_Service_Sheets($client);


$spreadsheetId = "14B0iB8-uLFNkb_d0qY183wNXeW5reAW5QBjOf69VXeU"; //It is present in the spreadsheet URL

//Adding the data in your google sheet

$update_range = 'data';

$values = [[ $name_kanji, $name_katakana, $age, $phone, $userEmail, $zip_code.', '.$city.', '.$address1.', '.$address2, $experience, $others_text, $lessons, $source]];

$body = new Google_Service_Sheets_ValueRange([
'values' => $values
]);

$params = [
'valueInputOption' => 'RAW'
];

$insert = [
    'insertDataOption' => 'INSERT_ROWS'
];

$update_sheet = $service->spreadsheets_values->append($spreadsheetId, $update_range, $body, $params);

我的问题在于以下代码

$values = [[ $name_kanji, $name_katakana, $age, $phone, $userEmail, $zip_code.', '.$city.', '.$address1.', '.$address2, $experience, $others_text, $lessons, $source]];

这里 $lessons 在数组中,其数据应该用逗号填充,或者在电子表格的 I 列中的列表中填充。

我可以获得有关如何传递数组数据的解决方案吗?

标签: phpapigoogle-sheetsgoogle-sheets-api

解决方案


要将数组转换为逗号分隔的字符串,请使用implode 方法

样本:

$list = implode(', ', $lessons);
$values = [[ $name_kanji, $name_katakana, $age, $phone, $userEmail, $zip_code.', '.$city.', '.$address1.', '.$address2, $experience, $others_text, $list, $source]];

推荐阅读