programing

여러 어레이 요소를 설정 해제하는 더 좋은 방법

minecode 2022. 11. 30. 21:19
반응형

여러 어레이 요소를 설정 해제하는 더 좋은 방법

17개의 요소를 가진 배열이 있습니다.일정 시간 동안 필요한 요소를 가져와 배열에서 영구적으로 제거하고 싶습니다.

코드는 다음과 같습니다.

$name = $post['name'];
$email = $post['email'];
$address = $post['address'];
$telephone = $post['telephone'];
$country = $post['country'];

unset($post['name']);
unset($post['email']);
unset($post['address']);
unset($post['telephone']);
unset($post['country']);

네, 코드가 추악해요. 때릴 필요 없어요.어떻게 하면 더 잘 보일까?

삭제에 사용

$remove = ['telephone', 'country'];

$removed = array_diff_key($post, array_flip($remove));

보관할 키 배열을 제공하려는 경우 를 사용할 수 있습니다.

이 함수는 수행하려는 작업에 더 적합한 도구인 것 같습니다(배열에서 모든 키/값을 추출하여 로컬 스코프의 키와 같은 이름의 변수에 할당하는 것으로 가정합니다).내용을 추출한 후 전체 설정을 해제할 수 있습니다.$post당신이 원하는 다른 건 아무것도 들어있지 않다고 가정했을 때요

다만, 실제로 질문에 답하기 위해서, 삭제할 키의 배열을 작성해, 루프 스루 해 명시적으로 설정을 해제할 수 있습니다.

$removeKeys = array('name', 'email');

foreach($removeKeys as $key) {
   unset($arr[$key]);
}

...또는 키가 제거된 새 어레이를 변수를 가리킬 수 있습니다.

$arr = array_diff_key($arr, array_flip($removeKeys));

...또는 모든 어레이 구성원을 다음 주소로 전달합니다.unset()...

unset($arr['name'],  $arr['email']);

위의 예보다 더 나은 방법이 있습니다.출처 : http://php.net/manual/en/function.unset.php

어레이 전체를 루프하여 모든 키를 설정하지 않고 다음과 같이 한 번만 설정을 해제할 수 있습니다.

어레이의 예:

$array = array("key1", "key2", "key3");

어레이 전체:

unset($array);

고유 키의 경우:

unset($array["key1"]);

하나의 어레이에 여러 키가 있는 경우:

unset($array["key1"], $array["key2"], $array["key3"] ....) and so on.

이것이 당신의 발전에 도움이 되기를 바랍니다.

이 질문이 오래된 것은 알지만, 최적의 방법은 다음과 같습니다.

$vars = array('name', 'email', 'address', 'phone'); /* needed variables */
foreach ($vars as $var) {
    ${$var} = $_POST[$var]; /* create variable on-the-fly */
    unset($_POST[$var]); /* unset variable after use */
}

이제 $name, $email 등을 어디서든 사용할 수 있게 되었습니다.

nB: extract()는 안전하지 않기 때문에 전혀 문제 없습니다!

<?php
   $name = $post['name'];
   $email = $post['email'];
   $address = $post['address'];
   $telephone = $post['telephone'];
   $country = $post['country'];



   
   $myArray = array_except($post, ['name', 'email','address','telephone','country']);
   
  print_r($myArray);
  
  
   
  function array_except($array, $keys){
    foreach($keys as $key){
        unset($array[$key]);
    }
    return $array;
  }
?>

in php unset 함수는 여러 인수를 사용할 수 있습니다.

$test = ['test1' => 1, 'test2' => 4, 'test34' => 34];

unset($test['test1'], $test['test34']);

다음은 설명서의 설명입니다.

unset(mixed $var, mixed ...$vars): void

언급URL : https://stackoverflow.com/questions/7884991/better-way-to-unset-multiple-array-elements

반응형