2

I'm trying to post and receive a two dimensional array, but I can't get it to work.

Could you guys help me out?

Thanks in advance!

Here is my code:

$items[] = array(
  'pid' => $pid
  , 'qty' => $product_qty
);    

<input type="hidden" name="items[]" id="pid" />

foreach ($_POST['items'] as $row) {
  $pid = $row['pid'];
  $product_qty = $row['qty'];
}
1
  • Do print_r($_POST); and you see the structure of your array and with which keys you can access it. Commented Mar 5, 2016 at 0:29

2 Answers 2

3

Change your code in a way like this:

$items = array('pid' => $pid, 'qty' => $product_qty);
foreach( $items as $key => $val )
{
    echo '<input type="hidden" name="items['.$key.']" value="'.$val.'" id="'.$key.'" />';
}

In your original code, $items[] add a new item to array $items.

Also, HTML doesn't interpret php variables, so your <input name="items[]" will produce $_POST[items][0] with an empty value.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! but what do i do on the receiving end?
You will receive yr example's expected $POST => $_POST['items']['pid'] etc... Also note that in my example there is id attribute, as per yr code, but the id attribute is not sent with $_POST
The submitting and receiving works but when i remove the brackets after $items the array displays two times the last loop :(
I don't understand. What loop? $items loop or $_POST loop?
the $items loop, sorry i forgot to mention $items[] = array('pid' => $pid, 'qty' => $product_qty); is in a foreach loop
|
0

It's as simple as this:

$myarr = array( 'pid' => array($pid), 'qty' => array($product_qty)); 

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.