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

时间:2016-10-26 20:58:07

标签: php arrays multidimensional-array

我有一个有两个维度的数组。它看起来像这样:

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,
    )
)

如果有相同ID的产品,我想将数量增加1。

我的代码如下:

    // 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 个答案:

答案 0 :(得分:1)

我对您的代码进行了更改,这应该是您想要实现的目标:

// 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;
}