PHP结合Google Sheets API:如何遍历数据并筛选展示指定ID的记录
Solution: Filter Records by Specified ID
To display only the record matching your target ID, you'll need to add a conditional check inside your foreach loop. Here's how to modify your code step by step:
Define your target ID: First, set a variable with the ID you want to show (replace
123with your actual target ID value):$targetId = '123'; // Replace with your desired ID (adjust data type if needed)Add the condition to your loop: Insert an
ifstatement inside theforeachto check if the current record's ID matches your target. Only render the table row if the condition is true.
Modified Code:
<?php } else{ echo $message; $targetId = '123'; // Replace with your actual target ID here foreach ($values as $value) { $countRow++; // Check if current record's ID matches the target if($value[0] == $targetId): ?> <tr> <form method='post' action='' id="form<?=$countRow?>"> <td><input class='inputRow' id="number<?=$countRow?>" readonly='' type='text' name='number' value="<?=$value[0]?>"></td> <td><input class='inputRow' id="docdate<?=$countRow?>" readonly='' type='text' name='docdate' value="<?=$value[1]?>"> <input type='hidden' name='row' value="<?=$countRow?>"></td> <td><input class='inputButton' id="btn<?=$countRow?>" type='submit' name='update' value='update'> <a href="javascript:void(0)" class="deleteClass" onclick="btnData(this.id)" id="bt-<?=$countRow?>">Edit</a> <input class='deleteClass' id="btnDelete<?=$countRow?>" type='submit' name='delete' value='Delete'> </td> </form> </tr> <?php endif; // End of the ID check condition } } ?>
Key Changes Explained:
- Target ID Variable: We added
$targetIdto store the ID you want to filter for. If your ID is numeric (not a string), remove the quotes (e.g.,$targetId = 123;). - Conditional Rendering: The
if($value[0] == $targetId)check ensures that only the record where the first element of the$valuearray (your ID field) matches the target is rendered. Non-matching records are skipped entirely.
If your ID is stored in a different column of your Google Sheet (not the first one), just replace $value[0] with the correct index (e.g., $value[2] for the third column).
内容的提问来源于stack exchange,提问作者accounting mtb21
相关产品推荐
相关产品推荐

