首页 > 解决方案 > Convert html form array to formated json array

问题描述

I have html input array. I want to collect the input values and return custom formatted json array. I loop through the form array and tried to collect all.

<input type="text" name="item_name[{{ i }}]">
<input type="number" name="item_price[{{ i }}]">

$item_price = $_POST['item_price'];
foreach(array_filter($_POST['item_name']) as $key => $value){

    $data = array('item_name'=>$value,     'item_price'=>$item_price[$key]);

    $data = array_merge($data, $data);
}
echo json_encode($data);

I want the result to be exactly like this format, having all the inputs thus. But my result only give one option, should the form request 3 items

{
  "1": {
    "item_name": "GOAT",
    "item_price": "200"
  },
  "2": {
    "item_name": "BEEF",
    "item_price": "150"
  },
  "3": {
    "item_name": "RAT",
    "item_price": "0"
  }
}

标签: phparrays

解决方案


You overwriting the $data var each time. You should append him the data with [] as:

foreach(array_filter($_POST['item_name']) as $key => $value){
    $data[] = array('item_name'=>$value, 'item_price'=>$item_price[$key]);
}
echo json_encode($data);

推荐阅读