Было бы намного проще преобразовать $_SESSION['cart']
в массив, чем объединять несколько идентификаторов в строку с разделителями. Затем вы можете использовать array_filter()
и array_search()
.
public function addItemToCart($id) {
# Filter through cart for the ID
$cartProduct = array_filter($_SESSION['cart'], function($product) use($id) {
$product = (object) $product;
return (int) $product->id == (int) $id;
});
# If the ID exists, increase quantity
if (!empty($cartProduct)) {
$product = (object) $cartProduct[0];
++$_SESSION['cart'][array_search(
(int) $product->id,
$_SESSION['cart'])]['quantity'];
return;
}
# If the ID does not exist, add new ID
$_SESSION['cart'][] = ['id' => $id, 'quantity' => 1];
}
function removeItemFromCart($id) {
# Update cart with the removed item
$_SESSION['cart'] = array_filter($_SESSION['cart'], function($product) {
$product = (object) $product;
return (int) $product->id != (int) $id;
});
}
Затем для доступа к корзине вы можете использовать:
function getItemsFromCart($callback) {
if(!is_callable($callback)) return false; # Ensure it is a Closure
foreach($_SESSION['cart'] as $product) call_user_func($callback, (object) $product); # Pass every array as an object to the function
}
Что можно использовать так:
getItemsFromCart(function($product) {
# $product will be used for every product inside the cart with ->id and ->quantity
# Recommend making this a static call to get a connection rather than opening multiple - just demonstration purposes.
$stmt = (new PDO('dsn', 'user', 'pass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
]))->Prepare('SELECT cost FROM myProductTable WHERE productId = ? LIMIT 1');
$stmt->execute(array((int) $product->id));
$cost = ((object) $stmt->fetch())->cost * (int) $product->quantity; # Here is your cost :)
});