Delete element from multidimensional-array based on value
Solution 1:
Try this:
function removeElementWithValue($array, $key, $value){
foreach($array as $subKey => $subArray){
if($subArray[$key] == $value){
unset($array[$subKey]);
}
}
return $array;
}
Then you would call it like this:
$array = removeElementWithValue($array, "year", 2011);
Solution 2:
Try this:
function remove_element_by_value($arr, $val) {
$return = array();
foreach($arr as $k => $v) {
if(is_array($v)) {
$return[$k] = remove_element_by_value($v, $val); //recursion
continue;
}
if($v == $val) continue;
$return[$k] = $v;
}
return $return;
}
Solution 3:
$array[] = array('year' => 2010, "genres_text" => "Drama / Komedie");
$array[] = array('year' => 2011, "genres_text" => "Actie / Thriller");
$array[] = array('year' => "2010", "genres_text" => "Drama / Komedie");
$array[] = array('year' => 2011, "genres_text" => "Romance");
print_r(remove_elm($array, "year", 2010)); // removes the first sub-array only
print_r(remove_elm($array, "year", 201)); // will not remove anything
print_r(remove_elm($array, "genres_text", "drama", TRUE)); // removes all Drama
print_r(remove_elm($array, "year", 2011, TRUE)); // removes all 2011
function remove_elm($arr, $key, $val, $within = FALSE) {
foreach ($arr as $i => $array)
if ($within && stripos($array[$key], $val) !== FALSE && (gettype($val) === gettype($array[$key])))
unset($arr[$i]);
elseif ($array[$key] === $val)
unset($arr[$i]);
return array_values($arr);
}