Google Sheets API:如果一行中有空白单元格,它将返回一个完全为空的行 更新:

问题描述

我正在使用PHP从工作表中收集数据。我正在丢失信息,因为如果有任何空白单元格,Google会删除整行。

$array是指从Google表格中收集的一些数据:

$range = "Sheet1!A1:C99";
$response = $service->spreadsheets_values->get($spreadsheetId,$range);
$array = $response->getValues();

但是工作表中的某些单元格为空,并且如果其中任何一个单元格位于行的左边界或右边界,Google都会删除该行中的所有数据。 [2] => [3]

一个question similar to this one,但是,它不是PHP的示例,我不能在这里应用它。

解决方法

Range.getValues()方法将返回一个二维值数组。您可以将其视为矩阵而不是数组,因为所有行将具有相同数量的“列”元素(即使它们在工作表中为空)。因此,罪魁祸首在其他地方 XD

考虑到这一点,请尝试以下操作:

$keys = array_shift($array); // Extract & exclude header row from $array
/*
Combine keys to each row in $array */
foreach ($array as &$row){
  $row = array_combine($keys,$row);
};
print_r($array);

更新:

Resource: ValueRangevalues[]字段中所述:“对于输出,将不包括空的尾随行和列。” 因此,您真的不能指望将这种方法用于您要寻找的目的。

作为替代方案,您可能要使用Apps脚本和我上面提到的Range.getValues()方法。

,

我付钱给人来解决这个问题,这就是他所做的:

// Update the order meta with value 
function action_woocommerce_checkout_update_order_meta( $order_id ) {
    // Meta value
    $meta_value = 'Company X';
    
    update_post_meta( $order_id,'merchant_identifier',$meta_value );
}
add_action( 'woocommerce_checkout_update_order_meta','action_woocommerce_checkout_update_order_meta',10,1 );

// OPTIONAL (will still work without this code,this is just to show it visually)
// Display field value on the order edit page
function action_woocommerce_admin_order_data_after_billing_address( $order ) {  
    echo '<p><strong>' . __( 'Merchant Identifier','woocommerce') . ':</strong> ' . $order->get_meta( 'merchant_identifier' ) . '</p>';
}
add_action( 'woocommerce_admin_order_data_after_billing_address','action_woocommerce_admin_order_data_after_billing_address',1 );

它确实起作用了!

谢谢