1

I am trying to remove pieces of a multidimensional array if a certain condition is met. The array can be as shown below, call it $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)

I have a function called is_followed, that let's me see if the id of one of the people in the array is being followed by the "user". The code I am trying is:

//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++;
}

The $id is the id of the current user.

However, this is not working. I know that using unset on $friend and not $friends is probably the issue. But using unset on $friends also won't work, because it is the higher level array. Any ideas? Thank you.

1
  • I'm not entirely sure, but I think the problem is with 'foreach'. I believe there was something about 'foreach working with a copy' or something. Try for($i; $i < count($friend); ++$i);? Commented Nov 7, 2014 at 7:55

2 Answers 2

1

If you're trying to take down the first parent keys, use the first foreach keys instead:

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

Or if only for that single friend:

foreach($friends as $friend) {
    foreach($friend as $i => $f) {
                  //   ^ this key
        if(Fanfollow::is_followed($id,$f->id)) {
            unset($friend[$i]);
            // unset this
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

array_filter comes to the rescue:

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

Though the solution with foreach is legit, array_filteris much more clear and sematically correct.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.