1

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"
  }
}
3
  • 3
    You are overwriting $data continously Commented Jun 26, 2019 at 12:11
  • Indeed. You need a global variable to store the final results. Commented Jun 26, 2019 at 12:12
  • 1
    As a shorthand, you could do $result[] = array('item_name'=>$value, 'item_price'=>$item_price[$key]); Commented Jun 26, 2019 at 12:13

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.