如何使用jQuery将多个输入框的数据转换为数组格式?
提取输入字段数据生成目标PHP数组格式
目标格式
array ( 'gender' => "male", "height" => "180", 'weight' => '90', 'value' => '#55' ), array ( 'gender' => "male", "height" => "177", 'weight' => '68', 'value' => '#66' ), array ( 'gender' => "female", "height" => "150", 'weight' => '55', 'value' => '#77' ),
待处理输入元素
<input type="text" gender='male' height='180' weight='90' value='#55' class='get-my-data'> <input type="text" gender='male' height='177' weight='68' value='#66' class='get-my-data'> <input type="text" gender='female' height='150' weight='55' value='#77' class='get-my-data'>
实现方案(JavaScript)
用以下代码可提取数据并生成匹配格式:
// 选中所有目标输入框 const inputs = document.querySelectorAll('.get-my-data'); // 生成结构化数组 const dataArray = Array.from(inputs).map(input => ({ gender: input.getAttribute('gender'), height: input.getAttribute('height'), weight: input.getAttribute('weight'), value: input.value })); // 转换为PHP数组格式字符串 function toPhpArrayString(arr) { return arr.map(item => `array ( 'gender' => "${item.gender}", "height" => "${item.height}", 'weight' => '${item.weight}', 'value' => '${item.value}' )`).join(',\n'); } // 输出结果到控制台,直接复制即可使用 console.log(toPhpArrayString(dataArray));
说明
- 通过类名选中所有需要处理的输入元素
- 遍历元素时,
gender/height/weight是自定义属性,用getAttribute获取;value是input标准属性,直接读取即可 - 转换函数会把JS数组转成你需要的PHP数组格式字符串,控制台输出后直接复制就能用
内容的提问来源于stack exchange,提问作者kovrita is The life
相关产品推荐
相关产品推荐

