문제
PHP를 사용하여 배열에서 요소를 삭제하는 쉬운 방법이 있습니까? foreach ($array)
더 이상 해당 요소를 포함하지 않습니까?
나는 그것을 설정한다고 생각했다 null
그렇게 하겠지만 분명히 작동하지 않는 것 같습니다.
해결책
배열 요소를 삭제하는 방법에는 여러 가지가 있으며, 그중 일부는 다른 것보다 특정 작업에 더 유용합니다.
하나의 배열 요소 삭제
배열 요소 하나만 삭제하려면 다음을 사용할 수 있습니다. \unset()
또는 대안적으로 \array_splice()
.
또한 값이 있고 요소를 삭제하는 키를 모르는 경우 사용할 수 있습니다. \array_search()
열쇠를 얻으러.
\unset()
방법
이용시 참고하세요 \unset()
배열 키는 변경/재인덱싱되지 않습니다.키를 다시 색인화하려면 다음을 사용할 수 있습니다. \array_values()
~ 후에 \unset()
모든 키를 0부터 시작하는 숫자 열거 키로 변환합니다.
암호
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
\unset($array[1]);
//↑ Key which you want to delete
?>
산출
[
[0] => a
[2] => c
]
\array_splice()
방법
당신이 사용하는 경우 \array_splice()
키는 자동으로 다시 색인화되지만 연관 키는 변경되지 않습니다. \array_values()
모든 키를 숫자 키로 변환합니다.
또한 \array_splice()
키가 아닌 오프셋이 필요합니다!두 번째 매개변수로
암호
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
//↑ Offset which you want to delete
?>
산출
[
[0] => a
[1] => c
]
array_splice()
같은 \unset()
참조로 배열을 가져옵니다. 이는 해당 함수의 반환 값을 배열에 다시 할당하고 싶지 않음을 의미합니다.
여러 배열 요소 삭제
여러 배열 요소를 삭제하고 호출을 원하지 않는 경우 \unset()
또는 \array_splice()
여러 번 기능을 사용할 수 있습니다 \array_diff()
또는 \array_diff_key()
삭제하려는 요소의 값이나 키를 알고 있는지 여부에 따라 다릅니다.
\array_diff()
방법
삭제하려는 배열 요소의 값을 알고 있다면 다음을 사용할 수 있습니다. \array_diff()
.이전과 마찬가지로 \unset()
배열의 키를 변경/재인덱싱하지 않습니다.
암호
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff($array, ["a", "c"]);
//└────────┘→ Array values which you want to delete
?>
산출
[
[1] => b
]
\array_diff_key()
방법
삭제하려는 요소의 키를 알고 있다면 다음을 사용하고 싶습니다. \array_diff_key()
.여기서는 키를 값이 아닌 두 번째 매개변수의 키로 전달해야 합니다.그렇지 않으면 다음을 사용하여 배열을 뒤집어야 합니다. \array_flip()
.또한 여기서 키는 변경/재인덱싱되지 않습니다.
암호
<?php
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
//↑ ↑ Array keys which you want to delete
?>
산출
[
[1] => b
]
또한 사용하고 싶다면 \unset()
또는 \array_splice()
사용할 수 있는 동일한 값을 가진 여러 요소를 삭제하려면 \array_keys()
특정 값에 대한 모든 키를 가져온 다음 모든 요소를 삭제합니다.
다른 팁
그것은 주목해야합니다 unset()
문자열 인덱스 (배열)를 사용할 때 예상되는 인덱스를 손대지 않게 유지하지만 정수 인덱스 어레이를 처리 할 때는 매우 놀라운 일입니다.
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[3]=>
int(3)
} */
$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
그래서 array_splice()
정수 키를 정상화하려면 사용할 수 있습니다. 다른 옵션은 사용 중입니다 array_values()
~ 후에 unset()
:
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
// Our initial array
$arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
print_r($arr);
// Remove the elements who's values are yellow or red
$arr = array_diff($arr, array("yellow", "red"));
print_r($arr);
위 코드의 출력은 다음과 같습니다.
Array
(
[0] => blue
[1] => green
[2] => red
[3] => yellow
[4] => green
[5] => orange
[6] => yellow
[7] => indigo
[8] => red
)
Array
(
[0] => blue
[1] => green
[4] => green
[5] => orange
[7] => indigo
)
이제 array_values()는 숫자 배열을 훌륭하게 다시 색인화하지만 배열에서 모든 키 문자열을 제거하고 숫자로 대체합니다.키 이름(문자열)을 유지해야 하거나 모든 키가 숫자인 경우 배열을 다시 색인화해야 하는 경우 array_merge()를 사용하세요.
$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);
출력
Array
(
[0] => blue
[1] => green
[2] => green
[3] => orange
[4] => indigo
)
$key = array_search($needle, $array);
if ($key !== false) {
unset($array[$key]);
}
unset($array[$index]);
모든 값이 고유한 숫자 인덱스 배열이 있는 경우(또는 고유하지 않지만 특정 값의 모든 인스턴스를 제거하려는 경우) 다음과 같이 간단히 array_diff()를 사용하여 일치하는 요소를 제거할 수 있습니다.
$my_array = array_diff($my_array, array('Value_to_remove'));
예를 들어:
$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);
그러면 다음이 표시됩니다.
4
3
이 예에서는 초기 배열에 대해 크기 4, 제거 후 3을 보고하는 sizeof() 호출을 통해 확인할 수 있듯이 'Charles' 값을 가진 요소가 제거됩니다.
또한 명명 된 요소의 경우 :
unset($array["elementName"]);
배열의 단일 요소를 파괴하십시오
unset()
$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);
출력은 다음과 같습니다.
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[3]=>
string(1) "D"
[4]=>
string(1) "E"
}
배열을 다시 인덱싱 해야하는 경우 :
$array1 = array_values($array1);
var_dump($array1);
그러면 출력은 다음과 같습니다.
array(4) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "D"
[3]=>
string(1) "E"
}
배열 끝에서 요소를 팝업하십시오 - 제거 된 요소의 값을 반환합니다
mixed array_pop(array &$array)
$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array
출력이 될 것입니다
Array
(
[0] => orange
[1] => banana
[2] => apple
)
Last Fruit: raspberry
배열에서 첫 번째 요소 (빨간색) 제거, - 제거 된 요소의 값을 반환합니다
mixed array_shift ( array &$array )
$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);
출력은 다음과 같습니다.
Array
(
[b] => green
[c] => blue
)
First Color: red
<?php
$stack = array("fruit1", "fruit2", "fruit3", "fruit4");
$fruit = array_shift($stack);
print_r($stack);
echo $fruit;
?>
산출:
Array
(
[0] => fruit2
[1] => fruit3
[2] => fruit4
)
fruit1
검색을 피하기 위해 array_diff
:
$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11
이 경우 키를 검색/사용할 필요가 없습니다.
배열에서 여러 값을 삭제 해야하는 경우 해당 배열의 항목이 객체 또는 구조화 된 데이터 인 경우 [array_filter][1]
당신의 최선의 방법입니다. 콜백 함수에서 True를 반환하는 항목은 유지됩니다.
$array = [
['x'=>1,'y'=>2,'z'=>3],
['x'=>2,'y'=>4,'z'=>6],
['x'=>3,'y'=>6,'z'=>9]
];
$results = array_filter($array, function($value) {
return $value['x'] > 2;
}); //=> [['x'=>3,'y'=>6,z=>'9']]
unset()
지정된 변수를 파괴합니다.
의 행동 unset()
기능 내부는 파괴하려는 변수 유형에 따라 다를 수 있습니다.
세계화 된 변수가있는 경우 unset()
함수 내부에는 로컬 변수 만 파괴됩니다. 통화 환경의 변수는 이전과 동일한 값을 유지합니다. unset()
부름 받았다.
<?php
function destroy_foo()
{
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
위의 코드의 답은입니다 술집.
에게 unset()
함수 내부의 글로벌 변수 :
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>
연관 배열
연관 배열의 경우 사용하십시오 unset
:
$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);
// RESULT: array('a' => 1, 'c' => 3)
숫자 배열
숫자 배열의 경우 사용하십시오 array_splice
:
$arr = array(1, 2, 3);
array_splice($arr, 1, 1);
// RESULT: array(0 => 1, 1 => 3)
메모
사용 unset
숫자 배열의 경우 오류가 발생하지 않지만 인덱스가 엉망이됩니다.
$arr = array(1, 2, 3);
unset($arr[1]);
// RESULT: array(0 => 1, 2 => 3)
연관 배열에서 여러 요소를 제거 해야하는 경우 사용할 수 있습니다. Array_diff_key () (여기서 사용되었습니다 Array_flip ()):
$my_array = array(
"key1" => "value 1",
"key2" => "value 2",
"key3" => "value 3",
"key4" => "value 4",
"key5" => "value 5",
);
$to_remove = array("key2", "key4");
$result = array_diff_key($my_array, array_flip($to_remove));
print_r($result);
산출:
Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 )
// Remove by value
function removeFromArr($arr, $val)
{
unset($arr[array_search($val, $arr)]);
return array_values($arr);
}
다음 배열이 있다고 가정합니다.
Array
(
[user_id] => 193
[storage] => 5
)
지우는 것 storage
, 하다:
unset($attributes['storage']);
$attributes = array_filter($attributes);
그리고 당신은 얻는다 :
Array
(
[user_id] => 193
)
나는 변수 속성을 가진 특정 객체를 가지고 있다고 말하고 싶습니다 (기본적으로 테이블을 매핑하고 테이블의 열을 변경하고 있었기 때문에 테이블을 반영하는 객체의 속성도 다릅니다).
class obj {
protected $fields = array('field1','field2');
protected $field1 = array();
protected $field2 = array();
protected loadfields(){}
// This will load the $field1 and $field2 with rows of data for the column they describe
protected function clearFields($num){
foreach($fields as $field) {
unset($this->$field[$num]);
// This did not work the line below worked
unset($this->{$field}[$num]); // You have to resolve $field first using {}
}
}
}
전체 목적 $fields
단지, 코드가 변경 될 때 코드의 모든 곳을 볼 필요가 없습니다. 수업의 시작 부분을보고 속성 목록과 $ Fields 새로운 속성을 반영하는 배열 컨텐츠.
기본 기능을 따르십시오.
나)
$Array = array("test1", "test2", "test3", "test3");
unset($Array[2]);
ii)
$Array = array("test1", "test2", "test3", "test3");
array_pop($Array);
iii)
$Array = array("test1", "test2", "test3", "test3");
array_splice($Array,1,2);
IV)
$Array = array("test1", "test2", "test3", "test3");
array_shift($Array);
솔루션:
- 하나의 요소를 삭제하려면 다음을 사용하십시오. 설정되지 않음():
unset($array[3]); unset($array['foo']);
- 연속되지 않은 여러 요소를 삭제하려면 다음도 사용하세요. 설정되지 않음():
unset($array[3], $array[5]); unset($array['foo'], $array['bar']);
- 여러 개의 연속된 요소를 삭제하려면 다음을 사용하세요. array_splice():
array_splice($array, $offset, $length);
추가 설명:
이러한 함수를 사용하면 PHP에서 해당 요소에 대한 모든 참조가 제거됩니다.배열에 키를 유지하고 싶지만 값이 비어 있는 경우 빈 문자열을 요소에 할당합니다.
$array[3] = $array['foo'] = '';
구문 외에도 다음을 사용하는 것에는 논리적 차이가 있습니다. 설정되지 않음() 요소에 ''를 할당합니다.첫 번째는 말한다 This doesn't exist anymore,
두 번째가 말하는 동안 This still exists, but its value is the empty string.
숫자를 다루는 경우 0을 할당하는 것이 더 나은 대안이 될 수 있습니다.따라서 회사가 XL1000 스프로킷 모델의 생산을 중단하면 다음과 같이 재고를 업데이트합니다.
unset($products['XL1000']);
그러나 일시적으로 XL1000 스프로킷이 부족하지만 이번 주 후반에 공장에서 새 배송을 받을 계획이라면 다음이 더 좋습니다.
$products['XL1000'] = 0;
만약 너라면 설정되지 않음() 요소인 경우, PHP는 루핑이 여전히 올바르게 작동하도록 배열을 조정합니다.누락된 구멍을 채우기 위해 배열을 압축하지 않습니다.모든 배열이 숫자로 보일 때에도 연관 배열이라고 말할 때 이것이 의미하는 바입니다.예는 다음과 같습니다.
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1]; // Prints 'bee'
print $animals[2]; // Prints 'cat'
count($animals); // Returns 6
// unset()
unset($animals[1]); // Removes element $animals[1] = 'bee'
print $animals[1]; // Prints '' and throws an E_NOTICE error
print $animals[2]; // Still prints 'cat'
count($animals); // Returns 5, even though $array[5] is 'fox'
// Add a new element
$animals[ ] = 'gnu'; // Add a new element (not Unix)
print $animals[1]; // Prints '', still empty
print $animals[6]; // Prints 'gnu', this is where 'gnu' ended up
count($animals); // Returns 6
// Assign ''
$animals[2] = ''; // Zero out value
print $animals[2]; // Prints ''
count($animals); // Returns 6, count does not decrease
배열을 조밀하게 채워진 숫자형 배열로 압축하려면 다음을 사용하십시오. 배열_값():
$animals = array_values($animals);
대안적으로, array_splice() 구멍이 남지 않도록 배열을 자동으로 다시 색인화합니다.
// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
[0] => ant
[1] => bee
[2] => elk
[3] => fox
)
이는 배열을 대기열로 사용하고 무작위 액세스를 허용하면서 대기열에서 항목을 제거하려는 경우에 유용합니다.배열에서 첫 번째 또는 마지막 요소를 안전하게 제거하려면 다음을 사용하십시오. 배열_시프트() 그리고 배열_팝(), 각각.
UnSet () 배열에서 다수의 조각난 요소
하는 동안 unset()
여기에 여러 번 언급되었지만 아직 언급되지 않았습니다. unset()
여러 변수를 허용하여 한 작업의 배열에서 여러 가지 비 연속 요소를 쉽게 삭제할 수 있습니다.
// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]
unset () 동적으로
Unset ()는 제거 할 키 배열을 허용하지 않으므로 아래 코드는 실패합니다 (Unset ()를 동적으로 사용하기가 약간 쉬워 졌을 것입니다).
$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);
대신, Unset ()는 Foreach 루프에서 동적으로 사용할 수 있습니다.
$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]
배열을 복사하여 배열 키를 제거하십시오
아직 언급되지 않은 또 다른 관행도 있습니다. 때로는 특정 배열 키를 제거하는 가장 간단한 방법은 $ array1을 $ array2로 간단히 복사하는 것입니다.
$array1 = range(1,10);
foreach ($array1 as $v) {
// Remove all even integers from the array
if( $v % 2 ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];
분명히 동일한 연습이 텍스트 문자열에 적용됩니다.
$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
// Remove all strings beginning with underscore
if( strpos($v,'_')===false ) {
$array2[] = $v;
}
}
print_r($array2);
// Output: [ 'foo', 'baz' ]
<?php
// If you want to remove a particular array element use this method
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
if (array_key_exists("key1", $my_array)) {
unset($my_array['key1']);
print_r($my_array);
}
else {
echo "Key does not exist";
}
?>
<?php
//To remove first array element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1);
print_r($new_array);
?>
<?php
echo "<br/> ";
// To remove first array element to length
// starts from first and remove two element
$my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
print_r($my_array);
$new_array = array_slice($my_array, 1, 2);
print_r($new_array);
?>
산출
Array ( [key1] => value 1 [key2] => value 2 [key3] =>
value 3 ) Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
Array ( [key2] => value 2 [key3] => value 3 )
키를 기반으로 배열 요소를 제거하십시오.
사용 unset
아래와 같이 기능 :
$a = array(
'salam',
'10',
1
);
unset($a[1]);
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
값에 따라 배열 요소를 제거하십시오.
사용 array_search
기능 요소 키를 얻고 위의 방식을 사용하여 아래와 같은 배열 요소를 제거하십시오.
$a = array(
'salam',
'10',
1
);
$key = array_search(10, $a);
if ($key !== false) {
unset($a[$key]);
}
print_r($a);
/*
Output:
Array
(
[0] => salam
[2] => 1
)
*/
<?php
$array = array("your array");
$array = array_diff($array, ["element you want to delete"]);
?>
변수에서 배열을 만듭니다 $array
그런 다음 내가 '요소를 삭제하고 싶은 곳'을 넣은 곳에 'a'와 같은 것을 넣었습니다. 여러 항목을 삭제하려면 "A", "B".
다음 코드를 사용하십시오.
$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
인덱스의 순서를 유지하여 배열의 첫 번째 항목을 제거하는 두 가지 방법과 첫 번째 항목의 키 이름을 모르는 경우.
해결책 #1
// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);
해결책 #2
// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);
이 샘플 데이터의 경우 :
$array = array(10 => "a", 20 => "b", 30 => "c");
이 결과가 있어야합니다.
array(2) {
[20]=>
string(1) "b"
[30]=>
string(1) "c"
}
Array_Search를 사용하여 키를 얻고 찾은 경우 UNSET로 제거하십시오.
if (($key = array_search('word', $array)) !== false) {
unset($array[$key]);
}
비 integer 키가있는 연관 배열의 경우 :
간단히, unset($array[$key])
작동 할 것이다.
정수 키가있는 배열 및 키를 유지하려는 경우 :
$array = [ 'mango', 'red', 'orange', 'grapes'];
unset($array[2]); $array = array_values($array);
array_splice($array, 2, 1);
도움이 될 수 있습니다 ...
<?php
$a1 = array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
$a2 = array("a"=>"purple", "b"=>"orange");
array_splice($a1, 0, 2, $a2);
print_r($a1);
?>
결과는 다음과 같습니다.
Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )
$arrayName = array( '1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
);
print_r($arrayName[1]);
// somevalue
unset($arrayName[1]);
print_r($arrayName);
unset
색인을 변경하지는 않지만 array_splice
하다:
$arrayName = array('1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
500 => 'somevalue500',
);
echo $arrayName['500'];
//somevalue500
array_splice($arrayName, 1, 2);
print_r($arrayName);
//Array ( [0] => somevalue [1] => somevalue500 )
$arrayName = array( '1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
500 => 'somevalue500',
);
echo $arrayName['500'];
//somevalue500
unset($arrayName[1]);
print_r($arrayName);
//Array ( [0] => somevalue [1] => somevalue500 )