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

如何根据Select选项切换Input值?基于同长度数组的PHP实现需求

嘿,这个商品选择联动价格的需求很常见,我给你拆解成PHP数据处理和前端交互两部分来实现,一步步来:

第一步:PHP端整理好商品与价格数据

首先你需要把商品名称、对应价格(还有商品编号如果需要的话)整理成数组,然后转成JSON格式传给前端,这样前端能方便地拿到对应关系。补全你的PHP代码:

<?php
// 假设$article是你从数据库或其他数据源拿到的商品集合
$arr_artnr = [];
$arr_artname = [];
$arr_price = [];

foreach($article as $art){
    $arr_artnr[] = $art["artnr"];
    $arr_artname[] = $art["artname"];
    $arr_price[] = $art["price"]; // 这里注意替换成你实际的价格字段名
}

// 将数据打包成JSON,方便前端读取
$product_data = json_encode([
    'names' => $arr_artname,
    'prices' => $arr_price,
    'nrs' => $arr_artnr
]);
?>
第二步:搭建前端HTML结构

我们需要一个<select>来展示商品选项,一个<input>来显示价格。这里可以用PHP循环直接生成选项,同时把PHP生成的JSON数据注入到JS变量中:

<!-- 先把PHP的商品数据转成JS可访问的变量 -->
<script>
const productList = <?php echo $product_data; ?>;
</script>

<!-- 商品选择下拉框 -->
<select id="productSelect">
    <?php foreach($arr_artname as $index => $artName): ?>
        <!-- 这里用索引作为option的value,方便直接对应价格数组的位置 -->
        <option value="<?php echo $index; ?>"><?php echo $artName; ?></option>
    <?php endforeach; ?>
</select>

<!-- 价格输入框,设置readonly可以防止用户手动修改,按需调整 -->
<input type="text" id="priceInput" readonly placeholder="请选择商品">
第三步:用JavaScript实现联动逻辑

监听下拉框的change事件,根据选中的选项索引,把对应位置的价格填充到输入框里,同时页面加载时默认填充第一个商品的价格:

const selectElement = document.getElementById('productSelect');
const priceInput = document.getElementById('priceInput');

// 页面加载完成后,默认填充第一个商品的价格
window.addEventListener('load', () => {
    const defaultIndex = selectElement.value;
    priceInput.value = productList.prices[defaultIndex];
});

// 监听下拉框选择变化
selectElement.addEventListener('change', (event) => {
    const selectedIndex = event.target.value;
    priceInput.value = productList.prices[selectedIndex];
});

可选优化:用商品编号作为选项值

如果你不想用索引,想用商品编号(artnr)作为<option>的value,可以调整代码:

调整HTML的选项生成:

<option value="<?php echo $arr_artnr[$index]; ?>"><?php echo $artName; ?></option>

调整JavaScript逻辑:

selectElement.addEventListener('change', (event) => {
    const selectedNr = event.target.value;
    // 找到该商品编号对应的数组索引
    const targetIndex = productList.nrs.indexOf(selectedNr);
    if (targetIndex !== -1) {
        priceInput.value = productList.prices[targetIndex];
    }
});

这样就完美实现了选商品自动填对应价格的功能啦~

内容的提问来源于stack exchange,提问作者Muchtar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:01:03