You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Define your target ID: First, set a variable with the ID you want to show (replace 123 with your actual target ID value):

    $targetId = '123'; // Replace with your desired ID (adjust data type if needed)
    
  2. Add the condition to your loop: Insert an if statement inside the foreach to 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 $targetId to 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 $value array (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:27:29