当我得到结果时,我得到的是数组格式的结果,这使我无法以所需的格式发布值。
我需要采用所需格式的结果(这些输入是从while循环中获取的):
<html>
<form>
<input type=text name=ref_id[] value=abc>
<input type=text name=qty[] value=12>
<input type=submit name=submit>
PHP脚本:
$data1 = array(
'delv_num' => $delv_num,
'hu_id' => $hu_id,
'box_scan_value' => $box_scan_value,
'type' => $type,
'hu_detail'=> array(
'reference_id'=> $_POST['ref_id'],
'qty' => $_POST['qty'] )
);
echo json_encode($data1);
我得到的结果如下:
{
"delv_num":"0006020715",
"hu_id":"HU000000000000000225",
"box_scan_value":"68889",
"type":"box",
"hu_detail":{
"reference_id":["TD0000000000991","TD0000000000990","TD0000000000767"],
"qty":["2","0","0"]
}
}
但是我需要以下格式的结果:
{
"delv_num":"0006020715",
"hu_id":"HU000000000000000225",
"box_scan_value":"68889",
"type":"box",
"hu_detail":[{
"reference_id":"TD0000000000991",
"qty":"2"
},
{
"reference_id":"TD0000000000990",
"qty":"0"
},
{
"reference_id":"TD0000000000767",
"qty":"0"
}
]
}
预先感谢
答案 0 :(得分:1)
您应该能够自己执行此操作。如果没有,则应再次通过php-basics:
$complete = [
'delv_num' => $delv_num,
'hu_id' => $hu_id,
'box_scan_value' => $box_scan_value,
'type' => $type,
'hu_detail' => []
];
foreach ($_POST['ref_id'] as $index => $refId) {
$huDetail = [
'reference_id'=> $refId,
'qty' => $_POST['qty'][$index]
];
$complete['hu_detail'][] = $huDetail;
}
echo json_encode($complete);
答案 1 :(得分:1)
只需更改输入名称即可更改表单的结构
function one(val) {
let result = '';
switch (val) {
case 'alpha':
result = 'Adams';
break;
case 'bravo':
result = 'Boston';
break;
};
return result;
}
function two(val) {
const lookup = {
'alpha': 'Adams',
'bravo': 'Boston',
};
return lookup[val] || '';
}
console.log('one:', one('alpha'));
console.log('two:', two('alpha'));
答案 2 :(得分:0)
尝试这样
$references = $_POST['ref_id'];
$qtys = $_POST['qty'];
$data = array(
'delv_num' => $delv_num,
'hu_id' => $hu_id,
'box_scan_value' => $box_scan_value,
'type' => $type,
);
$huDetails = [];
foreach($references as $index => $ref){
$huDetails[$index]['ref'] = $ref;
$huDetails[$index]['qty'] = $qtys[$index]; //assuming you have `ref` and `qty` has same number of index, if not then you need to modify your html structure
}
$data['hu_details'] = $huDetails;
print_r(json_encode($data))
答案 3 :(得分:0)
尝试这个:
$result = array();
$array_a = array("1","2","3");
$array_b = array("test1","test2","test3");
foreach($array_a as $key=> $value){
$result[$key]['reference_id'] = $value;
$result[$key]['qty'] = $array_b[$key];
}
$myJSONString = json_encode($result);
答案 4 :(得分:0)
在单个语句中可能的解决方案:
$data1 = [
'delv_num' => $delv_num,
'hu_id' => $hu_id,
'box_scan_value' => $box_scan_value,
'type' => $type,
'hu_detail' => array_map(
function ($id, $qty) {
return ['reference_id': $id, 'qty': $qty];
},
$_POST['ref_id'],
$_POST['qty']
),
];