Я думаю, что вы хотите использовать unset ()
//assuming $to contains the key in $users that needs to be removed
//from the array
unset($users[$to]);
Но поскольку $to
содержит массив ключей для элемента, а не один ключ к элементу, вам нужно написать свои собственные функции, чтобы делать то, что вы хотите.
Функция, которая делает то, что вам нужно, находится ниже, и удалит элемент данного массива с адресом в $ keys.
/**
* Removes the element with the keys in the array $keys
*
* @param haystack the array that contains the keys and values
* @param keys the array of keys that define the element to remove
* @return the new array
*/
function array_remove_bykeys( array $haystack, array $keys ){
//check if element couldn't be found
if ( empty($keys) ){
return $haystack;
}
$key = array_shift($keys);
if ( is_array($haystack[$key]) ){
$haystack[$key] = array_remove_bykeys($haystack[$key], $keys);
}else if ( isset($haystack[$key]) ){
unset($haystack[$key]);
}
return $haystack;
}
Другой метод - удалить все ключи со значением, которое вы искали.
/**
* Removes all elements from that array that has the value $needle
* @param $haystack the origanal array
* @param $needle the value to search for
* @return a new array with the value removed
*/
function array_remove_recursive( array $haystack, $needle ){
foreach( $haystack as $key => $value ) {
if( is_array($value) ) {
$haystack[$key] = array_remove_recursive($value, $needle);
} else if ( $value === $needle ){
unset($haystack[$key]);
}
}
return $haystack;
}
Для полноты (хотя демонстративно не рекомендуется), вот версия eval:
$keys = array(...);//an array of keys
//$arr is the variable name that contains the value that you want to remove
eval ('unset($arr[\''.implode('\'][\'', $keys).'\']);');