"ap...">

PHP - Removing a record from a multidimensional array

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 all keys in all child arrays and delete the entire child array if a search is found.

So basically:

  • When searching for "long", the entire array 2 is deleted.
  • If you are looking for an apple, the entire array 1 is deleted.

How to do it?

Thank!

+3
source share
4 answers

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;
        }
    }
}
+1
source

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

I have not tested the following, but it should work:

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

Here you go:

<?php
function deleteObjWithProperty($search,$arr)
  {
  foreach ($arr as &$val)
    {
    if (array_search($search,$val)!==false)
      {
      unlink($val);
      }
    }
  return $arr;
  }
?>
0
source
$_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>';
0
source

Source: https://habr.com/ru/post/1787517/


All Articles