我遇到了一个问题,无法在这个数组中删除一个
首先我获取要从数组中删除的
因此,逻辑将不再适用于应用程序的其余部分。
在删除
已解决:
object
。首先我获取要从数组中删除的
$id
。
但是当我筛选数组时,它会将键附加到数组上。因此,逻辑将不再适用于应用程序的其余部分。
在删除
cart
数组中的对象后,如何保持options
对象的相同语法?
public function destroy( $id, Request $request )
{
$user = $this->user ;
$data = array_filter( $user->options->cart , function ( $option ) use ( $id ) {
if ( $option->product_id == $id ) {
return false;
}
return json_encode($option);
});
//dd($user->options->cart);
//dd($data);
$user->options = (object)['cart' => $data ];
$user->save() ;
return response()->json( $user , 200 ) ;
}
已解决:
public function destroy( $id, Request $request )
{
$user = $this->user ;
$data = array_filter( $user->options->cart , function ( $option ) use ( $id ) {
if ( $option->product_id == $id ) {
return false;
}
return true;
});
$user->options = ['cart' => array_values( $data ) ];
$user->save() ;
return response()->json( $user , 200 ) ;
}
}
$this->user->options->cart
的数据是相同的。没有任何东西被移除。在这种情况下,unset函数无效。 - rocket_moon