i am working with PHP, I want to store more than two products in SESSION using array_push(). But problem is that after array_push only 2 products is showing in the cart. When i add more than two product then it is not added into the cart.
Here is my Code:
$dataArray = array();
$cartArray = array(
$code=>array(
'id' => $id,
'name' =>$name,
'price' =>$price,
'quantity' =>1)
);
if(empty($_SESSION["shopping_cart"])) {
$_SESSION["shopping_cart"] = $cartArray;
}
else {
array_push($dataArray, $_SESSION["shopping_cart"], $cartArray);
$_SESSION['shopping_cart'] = $dataArray;
}
You can directly assign values to an array like the below mention.
$_SESSION['shopping_cart'][] = $dataArray;
It will create a 2-d array for "shopping_cart" and every time you add $dataArray
it will store in new key so you can get the "shopping_cart" array having all items
For more about array go throgh this :- php arrays
Please find solution below:
<php
$cartArray = [
[
'id' => $id,
'name' =>$name,
'price' =>$price,
'quantity' =>1
],
[
'id' => $id,
'name' =>$name,
'price' =>$price,
'quantity' =>1
]
];
if(isset($_SESSION["shopping_cart"])){
if(empty($_SESSION["shopping_cart"])) {
$_SESSION["shopping_cart"] = $cartArray;
}
else {
array_push($_SESSION["shopping_cart"], $cartArray);
}
}
?>
Related
I have the following array
$data = [
[
'name' => 'Electric Khodro',
'price' => 12912
],
[
'name' => 'Iran Khodro',
'price' => 15218
],
[
'name' => 'Iran arghaam',
'price' => 8853
]
];
I want to get key of the maximum price name car from the array that is joy from the above array.
There are two tips in question:
If the value of the $ data variable was empty, the function must return the null value.
۲. The getHighestPrice function should have no parameters.
The general view of the codes is as follows:
<?php
$data = [
[
'name' => 'Electric Khodro',
'price' => 12912
],
[
'name' => 'Iran Khodro',
'price' => 15218
],
[
'name' => 'Iran arghaam',
'price' => 8853
]
,
// ...
];
function getHighestPrice()
{
// TODO: Implement
}
Thank you for helping in advance.
You can use array_column to get a one dimensional array from 'price'. php then has the function max() for the maximum.
$maxPrice = max(array_column($data,'price'));
The definition of a function only makes sense if it also uses parameters. Without parameters, you would have to work with global variables, but nobody in PHP doesn't do that.
function getHighestPrice($data,$name){
$prices = array_column($data,$name);
return $prices == [] ? NULL : max($prices);
}
$maxPrice = getHighestPrice($data,'price');
The function returns NULL if the array $data is empty or the name does not exist as a column.
Try self on 3v4l.org
As your requirement, If the getHighestPrice() function should have no parameters then you have to get the $data from global scope.
<?php
$data = [
[
'name' => 'Electric Khodro',
'price' => 12912
],
[
'name' => 'Iran Khodro',
'price' => 15218
],
[
'name' => 'Iran arghaam',
'price' => 8853
]
];
function getHighestPrice()
{
$data = $GLOBALS['data'] ?? null;// Get $data variable
if(empty($data)){
return null;// If empty then return null
}
// Sorting
usort($data, function($a, $b) {
return $a['price'] < $b['price'];
});
// Return the maximum price
return $data[0]['price'];
// Return the car name of maximum price
/*
return $data[0]['name'];
*/
}
echo getHighestPrice();
Output: 15218
I think you want the key of the highest value
$data = [
[
'name' => 'Electric Khodro',
'price' => 12912
],
[
'name' => 'Iran Khodro',
'price' => 15218
],
[
'name' => 'Iran arghaam',
'price' => 8853
]
];
echo(getHighestPrice($data));
function getHighestPrice($array = [])
{
$max = null;
$result = null;
foreach ($array as $key => $value) {
if ($max === null || $value['price'] > $max) {
$result = $key;
$max = $value['price'];
}
}
return $result;
}
OUTPUT:
1
enter image description here
Because we are sure that the data we have is not empty, we can first assume that the first cell of the given data is the maximum, so we put a variable called maxKey $ (which you put) and set it to zero.
Now in a quick h, we check if each item is worth more than the price at home maxKey $ or not, if so, we will update the value maxKey $.
Finally it is enough to return the value of data [$ maxKey] ['name'] $ (which is one of the problems with your current code is that you return the maximum value in immediate HR while there may be some more)
There is another problem with you: the value of $ key is not defined (in line 31) and also in For HH you have to compare the value of the item, which now compares the item itself, which is an associative array.
I need to fill an array with a dynamic list of products.
To do so, I'm using the following code:
$list_array = array(
$products[] = array(
'SKU' => '0001',
'Title' => 'Bread',
'Quantity' => '',
),
$products[] = array(
'SKU' => '0002',
'Title' => 'Butter',
'Quantity' => '',
)
);
return $list_array;
It works fine if I know every product in the array.
But in my use case I have no idea which products are in the array.
So I want to fill the array with dynamic data.
I came up with something this:
$products = get_posts( 'numberposts=-1&post_status=publish&post_type=product' );
foreach ( $products as $product ) {
$products[] = array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => '',
),
}
return $products;
I know there is something really wrong with the array. But I couldn't figure out what it is.
The code you submitted cannot work. The short syntax $a[] = ... is to append data to the $a array, for example:
$a = [];
$a[] = 1;
$a[] = 2;
// $a = [1, 2]
You can also do it in a more efficient way with a map function:
function reduce($product)
{
return array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => '',
);
}
return array_map('reduce', $products);
It will execute the function reduce and replace value for each element of you array. Complete doc here: https://www.php.net/manual/en/function.array-map.php
Your problem is that you are overwriting the $products array that you are looping over inside the loop. Change the name of the variable in the loop to fix that:
$list_array = array();
foreach ( $products as $product ) {
$list_array[] = array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => ''
);
}
return $list_array;
I'm inserting an array of multiple inputs. but when i dd it or create it doesn't insert or returning any values. How can i use create in this situation? I'm new to laravel.
foreach ($data['sku'] as $key => $val) {
$attrCountSKU = ProductsAttribute::where('sku', $val)->count();
if ($attrCountSKU > 0) {
return back()->with('error', 'SKU already exists for this product! Please input another SKU.');
}
$attrCountSizes = ProductsAttribute::where(['product_id' => $product->id, 'size' => $data['size'][$key]])->count();
if ($attrCountSizes > 0) {
return back()->with('error', 'Size already exists for this product! Please input another Size.');
}
$attribute = new ProductsAttribute;
$attribute->product_id = $product->id;
$attribute->sku = $val;
$attribute->size = $data['size'][$key];
$attribute->price = $data['price'][$key];
$attribute->stock = $data['stock'][$key];
dd($attribute);
dd($attribute->create());
}
You need to save the model, using the save() method.
Add this after setting all the attributes:
$attribute->save();
return $attribute->id // Will be set as the object has been inserted
You could also use the create() method to create and insert the model in one go:
$attribute = ProductsAttribute::create([
'product_id' => $product->id,
'sku' => $val,
'size' => $data['size'][$key],
'price' => $data['price'][$key],
'stock' => $data['stock'][$key],
]);
Laravel Docs: https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models
Instead of $attribute->create() you should use $attribute->save() method.
Or with the create() method you can do like this
$flight = ProductsAttribute::create(
[
'product_id' => $product->id,
'sku' => $val,
'size' => $data['size'][$key],
'price' => $data['price'][$key],
'stock' => $data['stock'][$key],
]
);
i store one array in to session('cart') last click [add to cart] , when i add another array in session('cart'), but it store one array then session can not save both.
help me !
public function addtocart(Request $req,$id){
$product = _prod::find($id)->toArray();
$item = [
'name' => $product['pName'],
'description' => $product['pDesc'],
'price' => $product['pPrice'],
];
$cart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => [$item]
];
$req->session()->put('cart',$cart);
$a = session()->get('cart');
}
change this
$req->session()->put('cart',$cart);
$a = session()->get('cart');
dd($a);
to this:
$cartvalues[] = $cart;
$req->session()->put('cart',$cartvalues);
$a = session('cart');
dd($a);
because you keep overwriting the previous value inside the session cart
Here you are overwriting cart variable in session every time you add a new item. So store cart items as an array and add item to array. Code should be:
public function addtocart(Request $req, $id) {
$product = _prod::find($id)->toArray();
$item = [
'name' => $product['pName'],
'description' => $product['pDesc'],
'price' => $product['pPrice'],
];
$cart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => [$item]
];
$cartItems = session()->get('cart');
if (empty($cartItems)) {
$cartItems = [];
}
$cartItems[] = $cart;
$req->session()->put('cart', $cartItems);
return view($cartItems);
}
Here is the simple example to update your cart in your case
`
public function addtocart(Request $req,$id){
//return redirect('Resouce/product');
$product = _prod::find($id)->toArray();
$item = [
'name' => $product['pName'],
'description' => $product['pDesc'],
'price' => $product['pPrice'],
];
if($req->session()->has('cart')){
$oldCart = $req->session()->get('cart');
$newCart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => array_merge($item,$oldCart['item'])
];
$req->session()->put('cart',$newCart);
}
$cart = [
'qtyTotal' => 0,
'priceTotal' => 0,
'item' => [$item]
];
$req->session()->put('cart',$cart);
$a = session()->get('cart');
dd($a);
}`
if ($cart = $this->cart->contents())
{
foreach ($cart as $item){
$order_detail = array(
'res_id' =>$this->session->userdata('menu_id[]'),
'customer_id' =>$coustomers,
'payment_id' =>$payment,
'name' => $item['name'],
'productid' => $item['id'],
'quantity' => $item['qty'],
'price' => $item['price'],
'subtotal' => $item['subtotal']
);
}
print_r($order_detail); exit;
when the foreach loop ends, only the last iteration value is left. I need all the values to be within the array.
Because order_detail will overwrite each time. Use array instead of simple variable.
$order_detail = array();
if ($cart = $this->cart->contents())
{
foreach ($cart as $item){
$order_detail[] = array(
'res_id' =>$this->session->userdata('menu_id[]'),
'customer_id' =>$coustomers,
'payment_id' =>$payment,
'name' => $item['name'],
'productid' => $item['id'],
'quantity' => $item['qty'],
'price' => $item['price'],
'subtotal' => $item['subtotal']
);
}
print_r($order_detail); exit;
Change this line
$order_detail = array(..);
to
$order_detail[] = array(..);
try this
first define the array
$order_detail=array();
array_push($order_detail, array(...));
array declaration must be outside the loop.