array nested problem in php

-1
  <?php
  session_start();
 if(isset($_GET['p'])){
$_SESSION['producto'][$_SESSION['contador']]['id'] = $_GET['p']; 
$_SESSION['contador']++;
} 
if(isset($_GET['c'])){
$_SESSION['producto'][$_SESSION['contador']]['can'] = $_GET['c'];
}

print_r($_SESSION['producto']);

result Array ([0] => Array ([can] = > 1 [id] = > 3) [1] = > Array ([id] = > 3) [2] = > Array ([ can] = > 1 [id] = > 3) [3] = > Array ([can] = > 1))

I do not know why only in position 0 are the 2 nested after they separate and how they would go through this array in a loop

    
asked by jose moya 23.10.2017 в 05:04
source

1 answer

0

The error is that you update the counter before entering the amount can , then following the logic you have:

  • It would be to verify if there is $_GET['p'] and it is not NULL , then $_SESSION['producto'][$_SESSION['contador']]['id'] = $_GET['p']; .
  • Then check if there is $_GET['c'] and it is not NULL , then $_SESSION['producto'][$_SESSION['contador']]['can'] = $_GET['c'];
  • Now if you increase the $_SESSION['contador']++; counter.
  • session_start();
    if(isset($_GET['p'])) {
        $_SESSION['producto'][$_SESSION['contador']]['id'] = $_GET['p']; 
        if(isset($_GET['c'])){
            $_SESSION['producto'][$_SESSION['contador']]['can'] = $_GET['c'];
        }
        $_SESSION['contador']++;
    }
    print_r($_SESSION['producto']);
    

    One way to go would be:

    foreach ($_SESSION['producto'] as $pro) { 
        print_r($pro);
        //así imprimiría por ejemplo (teniendo un solo producto con id = 1 y can = 3):  
        //Array ( [id] => 1 [can] => 3 )
    }
    
        
    answered by 23.10.2017 в 08:16