Tablica PHP Usuń według wartości (nie klucza)
Mam tablicę PHP w następujący sposób:
$messages = [312, 401, 1599, 3, ...];
Chcę usunąć element zawierający wartość $del_val
(na przykład $del_val=401
), ale nie znam jego klucza. Może to pomóc: Każda wartość może być tam tylko raz .
Szukam najprostszej funkcji do wykonania tego zadania proszę.
25 answers
Za pomocą array_search()
oraz unset
, spróbuj:
if (($key = array_search($del_val, $messages)) !== false) {
unset($messages[$key]);
}
array_search()
zwraca klucz elementu, który znajduje, który może być użyty do usunięcia tego elementu z oryginalnej tablicy za pomocą unset()
. Zwróci FALSE
W przypadku niepowodzenia, jednak może zwrócić wartość false-y w przypadku sukcesu (Twój klucz może być na przykład 0
), dlatego używany jest operator ścisłego porównania !==
.
Polecenie if()
sprawdzi, czy array_search()
zwróciło wartość i wykona tylko akcja, gdyby tak było.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-18 10:42:30
Cóż, usunięcie elementu z tablicy jest po prostu ustawioną różnicą z jednym elementem.
array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]
Ładnie uogólnia, możesz usunąć tyle elementów, ile chcesz w tym samym czasie, jeśli chcesz.
Zastrzeżenie: zauważ, że moje rozwiązanie tworzy nową kopię tablicy, zachowując starą nienaruszoną w przeciwieństwie do zaakceptowanej odpowiedzi, która mutuje. To może być trochę wolniejsze z tego powodu.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-25 10:16:37
Jednym z ciekawych sposobów jest użycie array_keys()
:
foreach (array_keys($messages, 401, true) as $key) {
unset($messages[$key]);
}
The array_keys()
funkcja pobiera dwa dodatkowe parametry, aby zwrócić tylko klucze dla określonej wartości i czy wymagane jest ścisłe sprawdzenie (tzn. użycie === dla porównania).
Może również usunąć wiele elementów tablicy o tej samej wartości (np. [1, 2, 3, 3, 4]
).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-14 06:48:23
Jeśli wiesz na pewno, że Twoja tablica będzie zawierać tylko jeden element o tej wartości, możesz zrobić
$key = array_search($del_val, $array);
if (false !== $key) {
unset($array[$key]);
}
Jeśli jednak wartość może wystąpić więcej niż jeden raz w tablicy, możesz to zrobić
$array = array_filter($array, function($e) use ($del_val) {
return ($e !== $del_val);
});
Uwaga: druga opcja działa tylko dla PHP5.3 + z zamknięciami
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-08 02:58:46
$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-01 17:26:59
Spójrz na następujący kod:
$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');
Możesz zrobić:
$arr = array_diff($arr, array('remove_me', 'remove_me_also'));
I to da ci tę tablicę:
array('nice_item', 'another_liked_item')
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-16 12:47:15
Za pomocą poniższego kodu, powtarzające się wartości zostaną usunięte z wiadomości$.
$messages = array_diff($messages, array(401));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-02 03:33:42
Najlepszym sposobem jest array_splice
array_splice($array, array_search(58, $array ), 1);
Reason for Best is here at http://www.programmerinterview.com/index.php/php-questions/how-to-delete-an-element-from-an-array-in-php/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-26 06:17:19
Lub po prostu, sposób ręczny:
foreach ($array as $key => $value){
if ($value == $target_value) {
unset($array[$key]);
}
}
To najbezpieczniejsze z nich, ponieważ masz pełną kontrolę nad swoją tablicą
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-22 19:03:32
function array_remove_by_value($array, $value)
{
return array_values(array_diff($array, array($value)));
}
$array = array(312, 401, 1599, 3);
$newarray = array_remove_by_value($array, 401);
print_r($newarray);
Wyjście
Array ( [0] => 312 [1] => 1599 [2] => 3 )
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-29 02:19:07
Aby usunąć wiele wartości, spróbuj użyć tego
while (($key = array_search($del_val, $messages)) !== false)
{
unset($messages[$key]);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-15 06:47:25
Możesz zrobić:
unset($messages[array_flip($messages)['401']]);
Wyjaśnienie: Usuń element, który ma klucz 401
po odwróceniu tablicy.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-09 08:50:06
Jeśli masz > php5. 3, jest jeden kod liniowy:
$array = array_filter($array, function($i) use ($value){return $i != $value;});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-05 04:34:34
Zapożyczył logikę underscoreJS _.odrzucić i stworzyć dwie funkcje (ludzie wolą funkcje!!)
Array_reject_value: Ta funkcja po prostu odrzuca określoną wartość (działa również dla PHP4,5,7)
function array_reject_value(array &$arrayToFilter, $deleteValue) {
$filteredArray = array();
foreach ($arrayToFilter as $key => $value) {
if ($value !== $deleteValue) {
$filteredArray[] = $value;
}
}
return $filteredArray;
}
Array_reject: Ta funkcja po prostu odrzuca metodę wywoływalną (działa dla PHP >=5.3)
function array_reject(array &$arrayToFilter, callable $rejectCallback) {
$filteredArray = array();
foreach ($arrayToFilter as $key => $value) {
if (!$rejectCallback($value, $key)) {
$filteredArray[] = $value;
}
}
return $filteredArray;
}
Więc w naszym obecnym przykładzie możemy używać powyższych funkcji w następujący sposób:
$messages = [312, 401, 1599, 3, 6];
$messages = array_reject_value($messages, 401);
Albo jeszcze lepiej: (bo to daje nam lepszą składnię aby użyć jak array_filter one)
$messages = [312, 401, 1599, 3, 6];
$messages = array_reject($messages, function ($value) {
return $value === 401;
});
Powyższe może być używane do bardziej skomplikowanych rzeczy, takich jak powiedzmy, że chcielibyśmy usunąć wszystkie wartości, które są większe lub równe 401, możemy po prostu zrobić to:
$messages = [312, 401, 1599, 3, 6];
$greaterOrEqualThan = 401;
$messages = array_reject($messages, function ($value) use $greaterOrEqualThan {
return $value >= $greaterOrEqualThan;
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-24 19:18:17
@ Bojangles odpowiedz mi pomogła. Dziękuję.
W moim przypadku tablica może być asocjacyjna lub nie, więc dodałem tę funkcję
function test($value, $tab) {
if(($key = array_search($value, $tab)) !== false) {
unset($tab[$key]); return true;
} else if (array_key_exists($value, $tab)){
unset($tab[$value]); return true;
} else {
return false; // the $value is not in the array $tab
}
}
Pozdrawiam
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-04 11:32:05
Pobierz klucz z array_search()
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-29 00:47:09
Jeśli wartości, które chcesz usunąć, są lub mogą być w tablicy. Użyj funkcji array_diff. Wygląda na to, że świetnie się sprawdza w takich sprawach.
$arrayWithValuesRemoved = array_diff($arrayOfData, $arrayOfValuesToRemove);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-08 23:56:34
OK.. Wiem, że to wcale nie jest wydajne, ale jest proste, intuicyjne i łatwe do odczytania.
Jeśli więc ktoś szuka nie tak wymyślnego rozwiązania, które można rozszerzyć na pracę z większą ilością wartości, lub bardziej specyficznymi warunkami .. Oto prosty kod:
$result = array();
$del_value = 401;
//$del_values = array(... all the values you don`t wont);
foreach($arr as $key =>$value){
if ($value !== $del_value){
$result[$key] = $value;
}
//if(!in_array($value, $del_values)){
// $result[$key] = $value;
//}
//if($this->validete($value)){
// $result[$key] = $value;
//}
}
return $result
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-05 16:22:46
Jeśli nie znasz jego klucza, to znaczy, że nie ma znaczenia.
Możesz umieścić wartość jako klucz, to znaczy, że natychmiast znajdzie wartość. Lepsze niż korzystanie z wyszukiwania we wszystkich elementach w kółko.
$messages=array();
$messages[312] = 312;
$messages[401] = 401;
$messages[1599] = 1599;
$messages[3] = 3;
unset($messages[3]); // no search needed
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-25 10:28:40
Zgodnie z Twoim wymaganiem "Każda wartość może być tam tylko raz " jeśli jesteś po prostu zainteresowany utrzymaniem unikalnych wartości w tablicy, to array_unique()
może tego szukasz.
Input:
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
Wynik:
array(2) {
[0] => int(4)
[2] => string(1) "3"
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-12 12:27:27
Lub jednowierszowy za pomocą operatora or
:
($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-13 00:43:08
Zaakceptowana odpowiedź konwertuje tablicę na tablicę asocjacyjną, więc jeśli chcesz zachować ją jako tablicę nie asocjacyjną z zaakceptowaną odpowiedzią, być może będziesz musiał użyć array_values
.
if(($key = array_search($del_val, $messages)) !== false) {
unset($messages[$key]);
$arr = array_values($messages);
}
Odniesienie jest tutaj
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:36
Możesz odnieść się do tego URL : dla funkcji
array-diff-key()
<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
var_dump(array_diff_key($array1, $array2));
?>
Wtedy wyjście powinno być,
array(2) {
["red"]=>
int(2)
["purple"]=>
int(4)
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-21 06:12:37
Single liner code (thanks to array_diff () ), use following:
$messages = array_diff($messages, array(401));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-29 11:13:37
Inny pomysł, aby usunąć wartość tablicy, użyj array_diff. If I want to
$my_array = array(1=>"a", "second_value"=>"b", 3=>"c", "d");
$new_array_without_value_c = array_diff($my_array, array("c"));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-24 17:17:54