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

Asked

Viewed 77 times

0

Eai rapazeada!
I’m making a prototype order system.
My idea: I have a list of products and when user clicks on 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 amount of requested items in a session. My problem is that I am unable to change the value of the second position of the two-dimensional array. I’ve asked apache to show me what the position value is and it shows, but if I need to add one or subtract one but it doesn’t change the original value.
Follows code:

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>";

1 answer

1

When you do the foreach($seuArray as $item), the $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 you indicate the foreach documentation.

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

Would 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>';
  • ,, thanks! had not understood yet why of this in the foreach. It worked perfectly with the adjustments that told me to do.

Browser other questions tagged

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