programing

PHP 배열 삭제 값(키 아님)

randomtip 2022. 12. 31. 18:20
반응형

PHP 배열 삭제 값(키 아님)

다음과 같은 PHP 어레이가 있습니다.

$messages = [312, 401, 1599, 3, ...];

합니다.$del_val (예:$del_val=401키를 모릅니다.이것은 도움이 될 수 있습니다.각 값은 1회밖에 사용할 수 없습니다.

이 작업을 수행할 수 있는 가장 간단한 기능을 찾고 있습니다.

및 를 사용하여 다음 작업을 수행합니다.

if (($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

array_search()검출된 이하여 원래 할 수 .이 키를 사용하여 원래 배열에서 해당 요소를 제거할 수 있습니다.unset().FALSE 시 성공할 수 에는 ", "false-y"가 ).0 이 한 비교가 .!==연산자가 사용됩니다.

if()에서는, 이 스테이트먼트가, 이 스테이트먼트의 를 확인합니다.array_search()값이 반환되었으며 반환된 경우에만 액션을 수행합니다.

어레이에서 요소를 삭제하는 것은 기본적으로 하나의 요소에 대해 설정된 차이입니다.

array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]

잘 일반화되어 있으면 동시에 원하는 만큼 요소를 제거할 수 있습니다.

면책사항:이 솔루션은 기존 어레이를 그대로 유지한 채 새로운 어레이 복사본을 생성합니다.이것에 의해 변환되는 기존의 답변과는 대조됩니다.필요한 걸 고르세요.

한 가지 흥미로운 방법은 다음을 사용하는 것입니다.

foreach (array_keys($messages, 401, true) as $key) {
    unset($messages[$key]);
}

함수는 두 개의 추가 파라미터를 사용하여 특정 값에 대한 키만 반환하고 엄격한 확인(예: 비교를 위해 === 사용)이 필요한지 여부를 확인합니다.

값을 「」등)을 삭제할 수도 .[1, 2, 3, 3, 4]를 참조해 주세요.

어레이에 그 값을 가진 요소가1개밖에 없는 것을 확실히 알고 있는 경우는, 다음과 같이 할 수 있습니다.

$key = array_search($del_val, $array);
if (false !== $key) {
    unset($array[$key]);
}

그러나 어레이에서 값이 여러 번 발생할 수 있는 경우 다음과 같이 할 수 있습니다.

$array = array_filter($array, function($e) use ($del_val) {
    return ($e !== $del_val);
});

주의: 두 번째 옵션은 Closes가 있는 PHP5.3+에서만 사용할 수 있습니다.

$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);

가장 좋은 방법은

array_splice($array, array_search(58, $array ), 1);

최적의 이유 http://www.programmerinterview.com/index.php/php-questions/how-to-delete-an-element-from-an-array-in-php/에 있습니다.

또는 간단히 말하면, 수동적인 방법:

foreach ($array as $key => $value){
    if ($value == $target_value) {
        unset($array[$key]);
    }
}

어레이를 완전히 제어할 수 있기 때문에 이것이 가장 안전합니다.

화살표 기능을 사용하는 PHP 7.4의 경우:

$messages = array_filter($messages, fn ($m) => $m != $del_val);

하려면 을 사용하여 .array_values():

$messages = array_values(array_filter($messages, fn ($m) => $m != $del_val));
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);

산출량

Array ( [0] => 312 [1] => 1599 [2] => 3 )

다음 작업을 수행할 수 있습니다.

unset($messages[array_flip($messages)['401']]);

설명:키가 있는 요소를 삭제합니다.401배열을 뒤집은 후.

여러 값을 삭제하려면 다음과 같이 하십시오.

while (($key = array_search($del_val, $messages)) !== false) 
{
    unset($messages[$key]);
}

수락된 답변은 어레이를 연관지을 수 있는 배열로 변환하기 때문에 수락된 답변과 연관지을 수 없는 배열로 유지하려면 를 사용해야 할 수 있습니다.array_values너무.

if(($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
    $arr = array_values($messages);
}

참조는 이쪽입니다.

만약 당신이 그것의 열쇠를 모른다면 그것은 중요하지 않다는 것을 의미한다.

값을 키로 지정할 수 있습니다. 즉, 즉시 값을 찾을 수 있습니다.모든 요소를 반복해서 검색하는 것보다 낫습니다.

$messages=array();   
$messages[312] = 312;    
$messages[401] = 401;   
$messages[1599] = 1599;   
$messages[3] = 3;    

unset($messages[3]); // no search needed

PHP 7.4 이상

function delArrValues(array $arr, array $remove) {
    return array_filter($arr, fn($e) => !in_array($e, $remove));
};

즉, 어레이가

$messages = [312, 401, 1599, 3];

둘 다 제거하고 싶다.3, 312$messages 배열에서 이렇게 하면

delArrValues($messages, [3, 312])

그것은 돌아올 것이다.

[401, 1599]

가장 좋은 점은 동일한 값의 항목이 여러 개 있더라도 여러 값을 쉽게 필터링할 수 있다는 것입니다.

언더스코어의 논리를 빌렸다.JS _.거부하여 2개의 함수를 만들었습니다(사람들은 함수를 선호합니다!!).

array_value:이 함수는 단순히 지정된 값을 거부하고 있습니다(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_module:이 함수는 단순히 호출 가능한 메서드를 거부하는 것입니다(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;
}

따라서 현재 예에서는 위의 함수를 다음과 같이 사용할 수 있습니다.

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject_value($messages, 401);

(array_filter와 같은 구문을 사용하는 것이 좋습니다)

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject($messages, function ($value) {
    return $value === 401;
});

예를 들어, 401보다 크거나 같은 값을 모두 삭제하고 싶은 경우, 다음과 같이 간단하게 할 수 있습니다.

$messages = [312, 401, 1599, 3, 6];
$greaterOrEqualThan = 401;
$messages = array_reject($messages, function ($value) use $greaterOrEqualThan {
    return $value >= $greaterOrEqualThan;
});

이것은 전혀 효율적이지 않다는 것을 알지만, 심플하고 직관적이며 읽기 쉽습니다.
그래서 만약 누군가가 더 많은 가치, 또는 더 구체적인 조건으로 일할 수 있도록 확장될 수 있는 그다지 화려하지 않은 해결책을 찾고 있다면…다음은 간단한 코드입니다.

$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

를 사용한 원라이너or연산자:

($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);

어레이 내에서 고유한 값을 유지하는 데 관심이 있는 경우 "각은 한 번만 존재할 있습니다"라는 요건에 따라 원하는 값이 될 수 있습니다.

입력:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

결과:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

가장 간단한 방법은 Foreach 루프가 있는 함수를 사용하는 것이라고 생각합니다.

//This functions deletes the elements of an array $original that are equivalent to the value $del_val
//The function works by reference, which means that the actual array used as parameter will be modified.

function delete_value(&$original, $del_val)
{
    //make a copy of the original, to avoid problems of modifying an array that is being currently iterated through
    $copy = $original;
    foreach ($original as $key => $value)
    {
        //for each value evaluate if it is equivalent to the one to be deleted, and if it is capture its key name.
        if($del_val === $value) $del_key[] = $key;
    };
    //If there was a value found, delete all its instances
    if($del_key !== null)
    {
        foreach ($del_key as $dk_i)
        {
            unset($original[$dk_i]);
        };
        //optional reordering of the keys. WARNING: only use it with arrays with numeric indexes!
        /*
        $copy = $original;
        $original = array();
        foreach ($copy as $value) {
            $original[] = $value;
        };
        */
        //the value was found and deleted
        return true;
    };
    //The value was not found, nothing was deleted
    return false;
};

$original = array(0,1,2,3,4,5,6,7,4);
$del_val = 4;
var_dump($original);
delete_value($original, $del_val);
var_dump($original);

출력은 다음과 같습니다.

array(9) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
  [8]=>
  int(4)
}
array(7) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
}

다음은 심플하지만 이해하기 쉬운 해결책입니다.

$messagesFiltered = [];
foreach ($messages as $message) {
    if (401 != $message) {
        $messagesFiltered[] = $message;
    }
}
$messages = $messagesFiltered;

언급URL : https://stackoverflow.com/questions/7225070/php-array-delete-by-value-not-key

반응형