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!
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]);
$_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>';