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:
How would I accomplish this?
Thanks!
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;
}
}
}
$_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>';
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]);
Here you go:
<?php
function deleteObjWithProperty($search,$arr)
{
foreach ($arr as &$val)
{
if (array_search($search,$val)!==false)
{
unlink($val);
}
}
return $arr;
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.