user1072337
user1072337

Reputation: 12945

Removing an item from a multidimensional array in php by value

I have a multidimensional array $array that looks like this:

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 would like to be able to remove one of the items in the array by searching for values (not indexes).

So, I would like to remove the item in the array that has the first_name property of 'Joe'.

So if I removed it, the array would look like this:

array (size=2)
  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)[502]
          public 'id' => int 1
          public 'first_name' => string 'Shag' (length=4)
          public 'last_name' => string 'Well' (length=4)

How would I be able to do this? Thanks.

Upvotes: 0

Views: 261

Answers (1)

Kevin
Kevin

Reputation: 41893

Yes you could just use a foreach in this case. It will work just fine. Just use your search string needle and add an if inside the loop comparing the objects property firstname and the needle:

$first_name_search = 'Joe';
foreach ($array as $key => $value) {
    $value = reset($value); // get that index 0 which is nested 
    if($value->first_name == $first_name_search) {
        unset($array[$key]);
    }
}

Upvotes: 2

Related Questions