laravel 通过php中的对象值从数组中删除对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33457834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:36:22  来源:igfitidea点击:

Remove Object from array by object value in php

phplaravel

提问by Guy Mazuz

$followers = [['id'=>0], ['id'=>1]];

So, assuming I have this array, what would be the best way to remove the object by it's id?

所以,假设我有这个数组,通过它的 id 删除对象的最佳方法是什么?

That's what i came up with

这就是我想出的

foreach($followers as $key=>$follower){
    if($follower->id == 0){unset $followers[$key]}
}

is there a better more efficient way?

有没有更好更有效的方法?

回答by Script47

It is an array not an object, so why are you accessing as an object?

它是一个数组而不是一个对象,那么你为什么要作为一个对象访问呢?

Try this,

尝试这个,

foreach ($followers as $key => $follower) {
    if($followers[$key] == 0) {
        unset($followers[$key]);
    }
}
  1. You were accessing values of an array like an object.

  2. You were using unsetincorrectly.

  3. You were missing the ;at the end of your unsetpart.

  1. 您正在像对象一样访问数组的值。

  2. 你用unset错了。

  3. 你错过了;unset部分的结尾。

回答by Guy Mazuz

What I really need is removing an item from array of arrays in my Cache I tried this:

我真正需要的是从我的缓存中的数组数组中删除一个项目我试过这个:

if(Cache::has('user_follower'.$user_id)){
        $user_follower = Cache::get('user_follower'.$user_id);

        foreach($user_follower as $key=>$follower){
            if($follower->user_id == Auth::id()){
                unset($user_follower[$key]);
                Cache::put('user_follower'.$user_id, $user_follower, 30);
                return;
            }
        }

}

I failed sadly, so I'm for now I'm using Cache::forget.

我很遗憾地失败了,所以我现在正在使用 Cache::forget。