1

我想在我的 google 电子表格中搜索包含字符串的特定列。我使用 PHP 从工作表中读取数据并将它们存储到一个数组中。打印数组会显示列值,但是当使用 (json_encode) 时,我只得到数组中的最后一个值,这很奇怪。

这是我的代码:

<?php
require 'vendor/autoload.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Publications</title>
<meta charset="utf-8">
</head>
<body>
    <?php
    $client = new \Google_Client();
    $client->setApplicationName('Google Sheets and PHP');
    $client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
    $client->setAccessType('offline');
    $credentials_file = __DIR__ . "/TestCase-641dce71a5df.json";
    $spreadsheetId = '1wP-NqVcGK9CBSPQRQ_oognVuKF07wsuiHjOAP0rQ3xI';
    $range = 'Responses!F2:F';
    $client->setAuthConfig($credentials_file);
    $service = new Google_Service_Sheets($client);
    $response = $service->spreadsheets_values->get($spreadsheetId, $range);
    $values = $response->getValues();
    if (empty($values)) {
        print "No data found.\n";
    } else {
        foreach ($values as $row) {
            $values_array = array($row[0]);
            echo "Normal:",json_encode($values_array), "\n";
        }
    }
    ?>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    var complexArray = <?php echo json_encode($values_array); ?>;
    console.log(complexArray);
    $("complexArray").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>
<h2>Filterable Table</h2>
<p>Type something in the input field to search</p>  
<input id="myInput" type="text" placeholder="Search..">
<br><br>
</body>
</html>
4

1 回答 1

1

您正在将数组重写为此处的最后一个值:

$values_array = array($row[0]);

尝试

var complexArray = <?php echo json_encode($values); ?>;
于 2020-02-24T05:56:21.887 回答