【问题标题】:How to remove a specific index from a multidimensional array in php如何从php中的多维数组中删除特定索引
【发布时间】:2014-11-07 07:52:17
【问题描述】:

如果满足某个条件,我正在尝试删除多维数组的片段。数组可以如下图,称之为$friends:

array (size=3)
  0 => 
    array (size=1)
      0 => 
        object(stdClass)[500]
          public 'id' => int 2
          public 'first_name' => string 'Mary' (length=4)
          public 'last_name' => string 'Sweet' (length=5)
  1 => 
    array (size=1)
      0 => 
        object(stdClass)[501]
          public 'id' => int 9
          public 'first_name' => string 'Joe' (length=3)
          public 'last_name' => string 'Bob' (length=3)
  2 => 
    array (size=1)
      0 => 
        object(stdClass)[502]
          public 'id' => int 1
          public 'first_name' => string 'Shag' (length=4)
          public 'last_name' => string 'Well' (length=4)

我有一个名为 is_followed 的函数,让我看看数组中的一个人的 id 是否被“用户”跟踪。我正在尝试的代码是:

//remove followed friends from the $friends array
$i=0;
foreach($friends as $friend) {
    foreach($friend as $f) {
        if(Fanfollow::is_followed($id,$f->id)) {
            unset($friend[$i]);
        }
    }
    $i++;
}

$id 是当前用户的 id。

但是,这不起作用。我知道在 $friend 而不是 $friends 上使用 unset 可能是问题所在。但是在 $friends 上使用 unset 也不起作用,因为它是更高级别的数组。有任何想法吗?谢谢你。

【问题讨论】:

  • 我不完全确定,但我认为问题出在“foreach”上。我相信有一些关于“foreach 使用副本”之类的东西。试试 for($i; $i

标签: php arrays multidimensional-array


【解决方案1】:

如果您尝试删除第一个父键,请改用第一个 foreach 键:

foreach($friends as $i => $friend) {
                //  ^ assign a key
    foreach($friend as $f) {
        if(Fanfollow::is_followed($id,$f->id)) {
            unset($friends[$i]);
            // unset this
        }
    }
}

或者,如果只是为了那个单身朋友:

foreach($friends as $friend) {
    foreach($friend as $i => $f) {
                  //   ^ this key
        if(Fanfollow::is_followed($id,$f->id)) {
            unset($friend[$i]);
            // unset this
        }
    }
}

【讨论】:

    【解决方案2】:

    array_filter 来救援:

    array_filter($friend, 
      function($f) use($id) { return Fanfollow::is_followed($id,$f->id)); }
    );
    

    虽然foreach 的解决方案是合法的,但array_filter 更清晰且语义正确。

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2021-11-07
      • 2019-02-05
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      相关资源
      最近更新 更多