Two-dimensional array does not change value of second array position

0

Eai rapazeada!
I'm doing a prototype ordering system.
My idea: I have a list of products and when the user clicks on the more or less of the item, I call a javascript function to change the quantity of the product and it calls via ajax a php routine that adjusts the quantity of the requested items in a session . My problem is that I can not change the value of the second position of the two-dimensional array. I've already asked apache to show me the value of the position and it shows, but if I need to add one or subtract one but it does not change the original value.

error_reporting(E_ALL);
session_start();
//unset($_SESSION['ItensPedido']);
//$codProd = $_GET['cod'];
//$conta = $_GET['conta'];
//$existe = 0;
$codProd = 20;
$conta = 1;
$existe = 0;
if(!isset($_SESSION['ItensPedido'])){
    $_SESSION['ItensPedido'] = array();
    array_push($_SESSION['ItensPedido'], array($codProd,1));
}else{
    foreach($_SESSION['ItensPedido'] as $item){
        if($item[0] == $codProd){
            if($conta == 1){
                $item[1] = $item[1] + 1;
                echo "<pre>", print_r($item, true),"</pre>";
            }else{
                if($item[1] != 0){
                    $item[1]--;
                }else{
                    unset($item);
                }
            }
        $existe++;
        }
    }

    if($existe == 0){
        array_push($_SESSION['ItensPedido'], array($codProd,1));
    }
}
echo "<pre>", print_r($_SESSION['ItensPedido'], true),"</pre>";
    
asked by anonymous 08.12.2016 / 13:25

1 answer

1

When you do foreach($seuArray as $item) , $item is a copy of the array element. By changing it, you are changing the copy and not the original item that is in the array.

To use the array item, you need to use a reference, as the foreach documentation a>.

Another thing, your unset needs to be using the array and its index, not the copy or reference of it. And this is also achieved with the foreach.

It would look something like this:

define ('IDX_PRODUTO', 0);
define ('IDX_QTD', 1);

// exemplo
$pedidos = array(
  // produto, quantidade
  array(1, 20),
  array(2, 40),
  array(3, 1)
);

echo "<pre>Antes do foreach:\n" . var_export($pedidos, true) . '</pre>';


foreach($pedidos as $idxItem => &$item) {
  if ($item[IDX_PRODUTO] === 1) {
    $item[IDX_QTD]++;
  } else {
    $item[IDX_QTD]--;
  }

  if ($item[IDX_QTD] <= 0) {
    unset($pedidos[$idxItem]);
  }
}
unset($item);

echo "<pre>\n\nApós foreach #3:\n" . var_export($pedidos, true) . '</pre>';
    
08.12.2016 / 14:33