I am new to Google Sheets API, Currently I'm developing a system to send data to Google Sheets. When I try to send data it shows error like: Invalid value [0][0]
Below are my lines of code.
`
$client = getClientAuth(); $spreadsheet_ID = $this->spreadsheet->spreadsheetId; $range = "Sheet1"; $values = $this->sheetData; $this->service = new Sheets($client); $body = new ValueRange([ 'majorDimension' => 'ROWS', 'values' => [array_map(function($nv) { return (is_null($nv)) ? "" : $nv; },$values)] ]); $params = ['valueInputOption' => 'RAW']; $insert = ['insertDataOption' => 'INSERT_ROWS']; //executing the request $data = $this->service->spreadsheets_values->append($spreadsheet_ID, $range, $body, $params, $insert); return $data;
`
P粉4468003292024-03-31 10:29:39
Based on your error message and display script, I think in your case $values
is probably a 2D array. I think your script will work if $values
is a 1D array. Also, include 'insertDataOption' => 'INSERT_ROWS'
in $params
. So, that being the case, what about the following modifications?
$body = new ValueRange([ 'majorDimension' => 'ROWS', 'values' => [array_map(function($nv) { return (is_null($nv)) ? "" : $nv; },$values)] ]); $params = ['valueInputOption' => 'RAW']; $insert = ['insertDataOption' => 'INSERT_ROWS']; //executing the request $data = $this->service->spreadsheets_values->append($spreadsheet_ID, $range, $body, $params, $insert);
$body = new ValueRange([ 'majorDimension' => 'ROWS', 'values' => array_map(function($row) { return array_map(function($col) { return (is_null($col)) ? "" : $col; }, $row); }, $values) ]); $params = ['valueInputOption' => 'RAW', 'insertDataOption' => 'INSERT_ROWS']; $data = $service->spreadsheets_values->append($spreadsheet_ID, $range, $body, $params);
or
$body = new Google_Service_Sheets_ValueRange([ 'majorDimension' => 'ROWS', 'values' => array_map(function($row) { return array_map(function($col) { return (is_null($col)) ? "" : $col; }, $row); }, $values) ]); $params = ['valueInputOption' => 'RAW', 'insertDataOption' => 'INSERT_ROWS']; $data = $service->spreadsheets_values->append($spreadsheet_ID, $range, $body, $params);
When using arrow functions, I think the following modifications can be used.
from
'values' => array_map(function($row) {
return array_map(function($col) {
return (is_null($col)) ? "" : $col;
}, $row);
}, $values)
To
'values' => array_map(fn($row) => array_map(fn($col) => (is_null($col)) ? "" : $col, $row), $values)