Split array according to payment types

0

index.php code

 <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 add-to-cart2.php page will receive the input's value and store in an array .

Page code add-to-cart2.php :

   session_start();

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

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

Using print_r will look like this:

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

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

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

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


)

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

I know that one of the errors I'm making is to assign the $ _ POST direct value to $ _ SESSION . I've made several changes but none have come close to what I want.

    
asked by anonymous 20.05.2017 / 20:44

1 answer

0

One way is to manually set the shape 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 both forms instead of array_push($_SESSION['cart'], $_POST) you will have the desired output.

    
20.05.2017 / 20:50