Split array according to payment types

Asked

Viewed 113 times

0

Code of index php.

 <form action="add-to-cart2.php" method="post">

   <label for="">Name</label>
   <input type="text" name="nome">
   <br> <br>

   <label for="">Dinheiro</label>
   <input type="text" name="dinheiro">
   <br> <br>

   <label for="">Cheque</label>
   <input type="text" name="cheque">
   <br> <br>

   <input type="submit" value="Submit">
</form>

As you can see, it’s a very simple form containing three fields.

The page add-to-cart2.php will receive the value of input’s and store in a array.

Page code add-to-cart2.php:

   session_start();

   if (empty($_SESSION['cart'])) {
      $_SESSION['cart'] = [];
   }

   array_push($_SESSION['cart'], $_POST);

When using the print_r will stay this way:

Array
(
    [nome] => Mathews
    [dinheiro] => 50
    [cheque] => 100
)

However, I would like the result to be something like a cash flow, that is, in this way:

Array
(
    [0] => Array
        (
            [nome] => Mathews
            [dinheiro] => 50
        )

    [1] => Array
        (
            [nome] => Mathews
            [cheque] => 100
        )


)

I am doing with $_SESSION as I am doing as a shopping cart, ie add / remove / change, all this in the same $_SESSION.

I know one of the mistakes I’m making is assigning the direct value of $_POST to the $_SESSION. I’ve made several changes but none have come close to what I wish.

1 answer

0


One way is to manually set the form you want to insert into the session. To add only the name and money fields:

array_push($_SESSION['cart'], ["nome" => $_POST['nome'], "dinheiro" => $_POST['dinheiro']]);

Or to add the name and check fields:

array_push($_SESSION['cart'], ["nome" => $_POST['nome'], "cheque" => $_POST['cheque']]);

Using the two forms instead of array_push($_SESSION['cart'], $_POST) you will have the desired exit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.