douquan3294
douquan3294
2017-11-17 15:44

使用PHP检查两个键是否存在数组

已采纳

I'd like to check if array exist by two keys: id and type

This code just check by id:

 if (isset($_POST['type'])) {
   $type = $_POST['type'];
 } 
 else {
   $type = '';
 }

 if (array_key_exists($id, $_SESSION['cart'])) {
        $_SESSION['cart'][$id]['quantity'] += $quantity;
    } else {
        $_SESSION['cart'][$id] = $line;
  }

I have tried with this code but it doesn't work:

 if (array_key_exists($id, $_SESSION['cart']) && array_key_exists($type, $_SESSION['cart'])) {
        $_SESSION['cart'][$id]['quantity'] += $quantity;
    } else {
        $_SESSION['cart'][$id] = $line;
    }

$_SESSION['cart'] is an array contains arrays of $line

 $line = array(
        'id' => $id,
        'type' => $type,
        'quantity' => $quantity,
        'price' => $price,
        'picture' => $dish->getPicture()->getWebPath(),
    );

This is the output of $_SESSION['cart']: enter image description here

As you see in th last array with id 55 and type "french bred" , what I'd like to do is to check if th user chose the same product but a with different type so insert new line else if the same product and the same type so just update quantity.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • drl971115 drl971115 4年前

    Something like this should do, however the question is too vague and too little code is shown for me to properly understand your problem

    $lineExists = false;
        foreach($_SESSION['cart'] as $index => $line){
            if($line['id'] === $id)
            {
                $_SESSION['cart'][$index]['quantity'] += $quantity;
                $lineExists = true;
            }
        }
        if(!$lineExists)
        {
            $_SESSION['cart'][] = $newLine;
        }
    
    点赞 评论 复制链接分享
  • dongtuoji5396 dongtuoji5396 4年前

    If you want to check if type and id exists then you should do something like this

    if (array_key_exists('id', $_SESSION['cart']) && array_key_exists('type', $_SESSION['cart'])) {
      // stuff here..
    }
    

    if $id is the value of the key id so 'id' => 5 then you should check like this:

    if ($_SESSION['cart']['type'] == $id) {
     // stuff here
    }
    

    Hope this somewhat helps you further!

    点赞 评论 复制链接分享