doufuhao8085 2016-10-26 20:58
浏览 40
已采纳

如果存在重复,则在多维数组中查找并更改值

I have an array with two dimensions. It looks like this:

Array (
[TOKEN] => c374fe5a38b49940b7794ea44185,
[0] => Array (
    [ID] => 1,
    [TITLE] => Product_1,
    [PRICE] => 14.99,
    [QTY] => 1,
    )
 [1] => Array (
    [ID] => 2,
    [TITLE] => Product_2,
    [PRICE] => 14.99,
    [QTY] => 1,
    )
)

I want to increase the value of quantity by one if there is a product with the same ID.

My Code looks like this:

    // PRODUCT DATA
    $res = mysqli_query($link, "SELECT * FROM products WHERE id='$pid'") or die(mysqli_error($link));
    $row = mysqli_fetch_array($res, MYSQLI_ASSOC);

    // PRODUCT ARRAY - PREPARE FOR INSERT IN ARRAY
    $product = array(
        "ID"    => $row['id'],
        "TITLE"    => $row['title'],
        "PRICE"    => $row['price'],
        "QTY"    => "1"
    );

    function array_search_recursive($needle, $haystack) {
        foreach ($haystack as $value) {
            if (is_array($value) && array_search_recursive($needle, $value)) return true;
            else if ($value == $needle) return true;
        }
        return false;
    }

    // PRODUCT ALREADY IN CART ARRAY?
    if(array_search_recursive($row['id'], $_SESSION['CART']) == TRUE){

       // INCREASE QTY BY ONE

    } else {

        // ADD PRODUCT TO ARRAY
        array_push($_SESSION['CART'], $product);

        return true;

    }

}

if(sh_add_cart($_GET['pid']) == TRUE){

    echo "PRODUCT ADDED.";

} else {
    echo "NOT ADDED.";
}
  • 写回答

1条回答 默认 最新

  • dongquelu1239 2016-10-26 21:04
    关注

    I made changes to your code which should do what you want to achieve:

    // PRODUCT ALREADY IN CART ARRAY?
    if(array_search_recursive($row['id'], $_SESSION['CART']) == TRUE){
    
       // INCREASE QTY BY ONE
       foreach ($_SESSION['CART'] as $key => $item) {
           if(is_array($item) && isset ($item['ID'] && (int) $item['ID'] === (int) $row['id']) {
               $_SESSION['CART'][$key]['QTY']++;
           }
       }
    
    } else {
        $_SESSION['CART'][] = $row;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?