3

I have an array like this:

$_SESSION['food'] = array( 

// ARRAY 1
array(
      "name" => "apple",
      "shape" => "round",
      "color" => "red"
  ),

// ARRAY 2
   array(
      "name" => "banana",
      "shape" => "long",
      "color" => "yellow"
  )
);

I want to search through all keys in all child arrays and delete the entire child array if the search term is found.

So, basically:

  1. If searching for "long", the entire Array 2 is removed.
  2. If searching for "apple", the entire Array 1 is removed.

How would I accomplish this?

Thanks!

1
  • Thanks everyone. I couldn't get any of the examples to work, but in the end I sorted it out by assigning each child array an associative key, which made it simple for me to find out the sub-array I need to delete. Thanks! Commented Jan 24, 2011 at 19:12

4 Answers 4

1

This should do the trick:

foreach ($array as $key => $value) {
    foreach ($value as $child_value) {
        if ($child_value == $search_term) {
            unset($array[$key]);
            continue 2;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Depending on how many dimensions you have, you can use array_search.

I haven't tested the following, but it should work:

$unset = array_search('apple', $_SESSION['food']);
unset($_SESSION['food'][$unset]);

1 Comment

This would not work. Array_search only searches the first level of an array.
0

Here you go:

<?php
function deleteObjWithProperty($search,$arr)
  {
  foreach ($arr as &$val)
    {
    if (array_search($search,$val)!==false)
      {
      unlink($val);
      }
    }
  return $arr;
  }
?>

Comments

0
$_SESSION['food'] = array( 

// ARRAY 1
array(
      "name" => "apple",
      "shape" => "round",
      "color" => "red"
 ),

// ARRAY 2
array(
     "name" => "banana",
     "shape" => "long",
     "color" => "yellow"
  )
);

echo '<pre>'.print_r($_SESSION['food']).'</pre>';

$arr_food = array();
$search_term = 'apple';

foreach($_SESSION['food'] AS $arr) {
   if($arr['name'] == $search_term) {
    unset($arr);
  }
$arr_food[] = $arr;
}

$_SESSION['food'] = $arr_food;
echo '<pre>'.print_r($_SESSION['food']).'</pre>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.