Reputation: 4527
I have this Array:
Array
(
[cart] => Array
(
[0] => Array
(
[id] => 1
[size] => XS
[count] => 1
)
[1] => Array
(
[id] => 2
[size] => XS
[count] => 1
)
)
)
How can I replace the array with id 2 in this multidimensional array for example?
I'm building an online-shop-system and want to add T-Shirts to a cart. If an article that already have been added would be added again, it should replace the cart-session-variable with the new input (new size, new count).
And how can I check if an specific id has already been added?
Upvotes: 0
Views: 74
Reputation: 30071
Since every product has its own unique id you could use the product id as the index in the array, then you would be able to do something like this:
// pseudo code
function add2Cart($product_id, $count, $size) {
global $cart;
$cart[$product_id] = array(
'count' => $count,
'size' => $size
);
)
Then you would have an array looking like:
[cart] => Array
(
[1] => Array
(
[size] => XS
[count] => 1
)
[2] => Array
(
[size] => XS
[count] => 1
)
)
Where each index is a products id number.
Upvotes: 0
Reputation: 4144
Given $cart with n products and $article as new an article to add:
$c = count($cart);
for($i=0;$i<$c;$i++) {
if ($cart[$i]['id'] == $article['id']) {
$cart[$i] = $article;
}
}
If u use the product_id as key just
if (isset($cart[$article['id']]) {
$cart[$article['id']] = $article;
}
Upvotes: 1
Reputation: 12872
Not sure exactly what your looking for but I think this will do it.
foreach ($array['cart'] as &$item) {
if ($item['id'] == $_POST['id']) {
$item = $_POST;
}
} unset($item);
Upvotes: 1