doushang8512 2014-11-17 20:46
浏览 25

php列出数组的每个键和值

i'm a beginner in php, so apologize if you will find the question a little weird.

i'm trying to check 2 variables that i POST and store in a session array. The 2 variables are the size and the color of an item in a shopping cart.

How can I check if theses 2 variables are already existing in my session array. If it's the case i just want to increment them quantity. In fact, i think i'm just missing to write my if statement for check this case. Here's the code:

   if (isset($_POST['ID']) && isset($_POST['SIZE']) && isset($_POST['COLOR'])) {

    $product = $_POST['ID'];
    $size = $_POST['SIZE'];
    $color = $_POST['COLOR'];

  $Found = false;
  $i = 0;
  // If the cart session variable is not set or cart array is empty
  if (!isset($_SESSION["myArray"]) || count($_SESSION["myArray"]) < 1) {
      // RUN IF THE CART IS EMPTY OR NOT SET
    $_SESSION["myArray"] = array(0 => array("productID" => $product, "quantity" => 1, "size"=> $size, "color" => $color));
  } else {
    // RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
    foreach ($_SESSION["myArray"] as $each_item) {
          $i++;
          while (list($key, $value) = each($each_item))
          {
            if (($key == "productID" && $value == $product))//<- IT'S PROBABLY WHERE I SHOULD CHECK THEM BUT HOW????
            {
              // That item is in cart already so let's adjust its quantity using array_splice()
              array_splice($_SESSION["myArray"], $i-1, 1, array(array("productID" => $product, "quantity" => $each_item['quantity'] + 1, "size"=> $size, "color" => $color)));
              $wasFound = true;
            } // close if condition
          } // close while loop
    } // close foreach loop
       if ($Found == false) {
         array_push($_SESSION["myArray"], array("productID" => $product, "quantity" => 1, "size"=> $size, "color" => $color));
       }
  }
}

Thanks in advance for your helps guys.

  • 写回答

2条回答 默认 最新

  • dongsu3654 2014-11-17 20:48
    关注

    You need to list key and value of an array ?

     foreach ($_SESSION["myArray"] as $key=>$each_item) {
    

    How can I check if theses 2 variables are already existing in my session array.

    if(array_key_exist('color',$_SESSION["myArray"]))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类