[英]how to remove the curly braces and user_cart string
public function addToCart($id){
$course = Course::findOrfail($id);
$user =Auth::user();
$cart_array = array();
$cart = $user->user_cart;
if ($cart == '') {
array_push($cart_array, array('user_cart' => $course->id));
// print_r($cart_array);
} else {
$founder = false;
$cart_array = json_decode($cart, true);
for ($i = 0; $i < count($cart_array); $i++) {
$cart_for_eacch_course = $cart_array[$i];
if ($cart_for_eacch_course['user_cart'] == $course->id) {
$founder = true;
}
}
if (!$founder) {
array_push($cart_array, array('user_cart' => $course->id));
}
}
$data['user_cart'] = json_encode($cart_array);
$update = User::where('id',$user->id)->update(['user_cart'=> $cart_array]);
Current Output当前Output
[{"user_cart":86},{"user_cart":84}]
Expected Output预计 Output
[84,86]
Now I am having the current Output but I want expected one.现在我有当前的 Output 但我想要一个。 I tried by removing the json_encode but it didn't work for me.
我尝试删除 json_encode 但它对我不起作用。
You can use array_column()
like so您可以像这样使用
array_column()
$new_array = array_column($cart_array, 'user_cart');
When you are creating the output array, you are using...当您创建 output 阵列时,您正在使用...
array_push($cart_array, array('user_cart' => $course->id));
which is why you get the sub arrays with the keys.这就是为什么你得到带有钥匙的子 arrays 的原因。 If instead you just add the
$course->id
values, then this should build the output in the first place rather than having to process it further...如果您只是添加
$course->id
值,那么这应该首先构建 output 而不必进一步处理它......
$cart_array[] = $course->id;
You would also need to change the line您还需要更改线路
if ($cart_for_eacch_course['user_cart'] == $course->id) {
to至
if ($cart_for_eacch_course == $course->id) {
as you no longer have the sub index.因为您不再拥有子索引。 You could change this part of the code to use
in_array()
instead which would also be shorter.您可以将这部分代码更改为使用
in_array()
,这也会更短。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.