嗨,我正在尝试从数组中删除一行。
例如:
array:1 [▼
5 => "2"
4 => "1"
]
键是ID,值是金额
如何在我的视图中仅删除1个单行而不删除整个数组?
我希望有人能帮助我!
这是我的购物车控制器:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use App\Category;
use App\Product;
class ShopController extends Controller
{
public function addToShoppingCart(Request $request)
{
$data = $this->validate($request, [
'id' => 'required|integer|min:1|max:2147483647',
'amount' => 'required|integer|min:1|max:100',
]);
$currentCart = $request->session()->get('cart');
if (!is_array($currentCart)) {
$currentCart = [];
}
if (array_key_exists($data['id'], $currentCart)){
$currentCart[$data['id']]+= $data['amount'];
}else{
$currentCart[$data['id']] = $data['amount'];
}
$request->session()->put('cart', $currentCart);
return Redirect()->action('ShopController@cart');
}
public function cart(Request $request)
{
$cart = $request->session()->get('cart');
return view('shop/cart', [
'cart' => (is_array($cart) ? $cart:[]),
]);
}
public function delete()
{
unset($_SESSION['cart']['id']);
return Redirect()->back();
}
}
这是我的购物车视图:
@extends('layouts.app')
@section('content')
@forelse ($cart as $id => $amount)
<div class="container">
<li>Product: {{$id}}, Hoeveelheid: {{$amount}}</li>
<a class="btn btn-danger" href="{{ action('ShopController@delete') }}">
Product verwijderen
</a>
<a href="{{ action('ShopController@clear') }}">Winkelwagen legen</a>
</div>
{{ dd($cart) }}
@empty
<div class="container">
Er is nog niks in uw winkelwagen!
</div>
@endforelse
@endsection
我希望有人能让我摆脱困境
答案 0 :(得分:0)
正如乔恩·斯特林(Jon Stirling)所指出的,您应该像这样使用unset:
unset($array[1]); // unsets element of $array with key of 1
示例:
$array = array(
5 => "2",
4 => "1"
);
unset($array[5]);
/**
Will output:
Array
(
[4] => 1
)
*/
print_r($array);
unset($array);
print_r($array); // Produces PHP Notice: Undefined variable: array in test.php on line 13