Programing

PHP는 연관 배열에서 요소를 제거

lottogame 2020. 8. 24. 20:50
반응형

PHP는 연관 배열에서 요소를 제거


다음과 같은 PHP 배열이 있습니다.

Index              Key     Value
[0]                1       Awaiting for Confirmation
[1]                2       Assigned
[2]                3       In Progress
[3]                4       Completed
[4]                5       Mark As Spam

내가 var_dump 배열 값을 얻을 때 나는 이것을 얻는다 :

array(5) { [0]=> array(2) { ["key"]=> string(1) "1" ["value"]=> string(25) "Awaiting for Confirmation" } [1]=> array(2) { ["key"]=> string(1) "2" ["value"]=> string(9) "Assigned" } [2]=> array(2) { ["key"]=> string(1) "3" ["value"]=> string(11) "In Progress" } [3]=> array(2) { ["key"]=> string(1) "4" ["value"]=> string(9) "Completed" } [4]=> array(2) { ["key"]=> string(1) "5" ["value"]=> string(12) "Mark As Spam" } }

완료 됨스팸으로 표시 를 제거 하고 싶었습니다 . 나는 할 수 있다는 것을 알고 unset[$array[3],$array[4])있지만 문제는 때때로 색인 번호가 다를 수 있다는 것입니다.

키 값 대신 값 이름을 일치시켜 제거하는 방법이 있습니까?


배열이 매우 이상합니다. as 인덱스와 as ... 값을 사용하지 않는 이유 는 무엇입니까?keyvalue

배열이 다음과 같이 선언 되었다면 훨씬 쉬울까요?

$array = array(
    1 => 'Awaiting for Confirmation', 
    2 => 'Asssigned', 
    3 => 'In Progress', 
    4 => 'Completed', 
    5 => 'Mark As Spam', 
);

그러면의 값을 key인덱스로 사용하여 배열에 액세스 할 수 있습니다.

그리고 다음과 같은 함수를 사용하여 값을 검색 할 수 있습니다 array_search().

$indexCompleted = array_search('Completed', $array);
unset($array[$indexCompleted]);

$indexSpam = array_search('Mark As Spam', $array);
unset($array[$indexSpam]);

var_dump($array);

어레이보다 더 쉽습니다.



대신 다음과 같은 배열을 사용하십시오.

$array = array(
    array('key' => 1, 'value' => 'Awaiting for Confirmation'), 
    array('key' => 2, 'value' => 'Asssigned'), 
    array('key' => 3, 'value' => 'In Progress'), 
    array('key' => 4, 'value' => 'Completed'), 
    array('key' => 5, 'value' => 'Mark As Spam'), 
);

모든 항목을 반복 value하고을 분석 하고 올바른 항목을 설정 해제해야합니다.

foreach ($array as $index => $data) {
    if ($data['value'] == 'Completed' || $data['value'] == 'Mark As Spam') {
        unset($array[$index]);
    }
}
var_dump($array);

할 수 있더라도 그렇게 간단하지 않습니다 ... 그리고 저는 주장합니다 : 더 간단한 키 / 값 시스템으로 작업하기 위해 배열의 형식을 변경할 수 없습니까?


  ...

  $array = array(
      1 => 'Awaiting for Confirmation', 
      2 => 'Asssigned', 
      3 => 'In Progress', 
      4 => 'Completed', 
      5 => 'Mark As Spam', 
  );



  return array_values($array);
  ...

$key = array_search("Mark As Spam", $array);
unset($array[$key]);

2D 배열의 경우 ...

$remove = array("Mark As Spam", "Completed");
foreach($arrays as $array){
    foreach($array as $key => $value){
        if(in_array($value, $remove)) unset($array[$key]);
    }
}

이것을 사용할 수 있습니다

unset($dataArray['key']);

array_diff를 사용하지 않는 이유는 무엇입니까?

$array = array(
    1 => 'Awaiting for Confirmation', 
    2 => 'Asssigned', 
    3 => 'In Progress', 
    4 => 'Completed', 
    5 => 'Mark As Spam', 
);
$to_delete = array('Completed', 'Mark As Spam');
$array = array_diff($array, $to_delete);

배열이 다시 인덱싱된다는 점에 유의하십시오.


이 시도:

$keys = array_keys($array, "Completed");

/ edit JohnP에서 언급했듯이이 방법은 비 중첩 배열에서만 작동합니다.


이를 수행하는 방법은 중첩 된 대상 배열을 가져 와서 단일 단계로 중첩되지 않은 배열에 복사하는 것입니다. 키를 삭제 한 다음 마지막으로 트리밍 된 배열을 이전 배열의 중첩 노드에 할당합니다. 다음은 간단하게 만드는 코드입니다.

$temp_array = $list['resultset'][0];

unset($temp_array['badkey1']);
unset($temp_array['badkey2']);

$list['resultset'][0] = $temp_array;

I kinda disagree with the accepted answer. Sometimes an application architecture doesn't want you to mess with the array id, or makes it inconvenient. For instance, I use CakePHP quite a lot, and a database query returns the primary key as a value in each record, very similar to the above.

Assuming the array is not stupidly large, I would use array_filter. This will create a copy of the array, minus the records you want to remove, which you can assign back to the original array variable.

Although this may seem inefficient it's actually very much in vogue these days to have variables be immutable, and the fact that most php array functions return a new array rather than futzing with the original implies that PHP kinda wants you to do this too. And the more you work with arrays, and realize how difficult and annoying the unset() function is, this approach makes a lot of sense.

Anyway:

$my_array = array_filter($my_array, 
                         function($el) { 
                            return $el["value"]!="Completed" && $el!["value"]!="Marked as Spam"; 
                         });

You can use whatever inclusion logic (eg. your id field) in the embedded function that you want.


for single array Item use reset($item)

참고URL : https://stackoverflow.com/questions/5450148/php-remove-elements-from-associative-array

반응형