IT

값으로 배열 항목 제거

lottoking 2020. 6. 3. 08:10
반응형

값으로 배열 항목 제거


주어진 값으로 배열 항목을 제거해야합니다.

if (in_array($id, $items)) {
    $items = array_flip($items);
    unset($items[ $id ]);
    $items = array_flip($items);
}

더 짧은 (보다 효율적인) 방식으로 수행 할 수 있습니까?


간단한 원 라이너로 달성 할 수 있습니다.

이 배열을 갖는 것 :

$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');

넌 할 수있어:

$arr = array_diff($arr, array('remove_me', 'remove_me_also'));

그리고 가치 $arr는 다음과 같습니다.

array('nice_item', 'another_liked_item')

그것이 아름다운 코드를 작성하는 데 도움이되기를 바랍니다.


두 번째 답변을 추가하고 있습니다. 다양한 방법을 시도하기 위해 빠른 벤치마킹 스크립트를 작성했습니다.

$arr = array(0 => 123456);
for($i = 1; $i < 500000; $i++) {
    $arr[$i] = rand(0,PHP_INT_MAX);
}

shuffle($arr);
$arr2 = $arr;
$arr3 = $arr;

/** 
 * Method 1 - array_search()
 */
$start = microtime(true);
while(($key = array_search(123456,$arr)) !== false) {
    unset($arr[$key]);
}
echo count($arr). ' left, in '.(microtime(true) - $start).' seconds<BR>';

/** 
 * Method 2 - basic loop
 */
$start = microtime(true);
foreach($arr2 as $k => $v) {
    if ($v == 123456) {
        unset($arr2[$k]);
    }
}
echo count($arr2). 'left, in '.(microtime(true) - $start).' seconds<BR>';

/** 
 * Method 3 - array_keys() with search parameter
 */
$start = microtime(true);
$keys = array_keys($arr3,123456);
foreach($keys as $k) {
    unset($arr3[$k]);
}
echo count($arr3). 'left, in '.(microtime(true) - $start).' seconds<BR>';

array_keys()선택적 검색 매개 변수가 지정된 세 번째 방법 은 지금까지 가장 좋은 방법 인 것 같습니다. 출력 예 :

499999 left, in 0.090957164764404 seconds
499999left, in 0.43156313896179 seconds
499999left, in 0.028877019882202 seconds

이것으로 판단하면 내가 사용할 솔루션은 다음과 같습니다.

$keysToRemove = array_keys($items,$id);
foreach($keysToRemove as $k) {
    unset($items[$k]);
}


어때요 :

if (($key = array_search($id, $items)) !== false) unset($items[$key]);

또는 여러 값의 경우 :

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

이렇게하면 키 손실도 방지 할 수 있으며 이는 부작용입니다 array_flip().


제거하는 방법 $rm_val에서$arr

unset($arr[array_search($rm_val, $arr)]);

가장 강력한 솔루션은을 사용 array_filter하는 것이므로 자체 필터링 기능을 정의 할 수 있습니다.

But some might say it's a bit overkill, in your situation...
A simple foreach loop to go trough the array and remove the item you don't want should be enough.

Something like this, in your case, should probably do the trick :

foreach ($items as $key => $value) {
    if ($value == $id) {
        unset($items[$key]);
        // If you know you only have one line to remove, you can decomment the next line, to stop looping
        //break;
    }
}

Try array_search()


Your solutions only work if you have unique values in your array

See:

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

A better way would be unset with array_search, in a loop if neccessary.


w/o flip:

<?php
foreach ($items as $key => $value) {
    if ($id === $value) {
        unset($items[$key]);
    }
}

function deleteValyeFromArray($array,$value)
{
   foreach($array as $key=>$val)
   {
      if($val == $value)
      {
         unset($array[$key]);
      }
   }
   return $array;
}

You can use array_splice function for this operation Ref : array_splice

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

참고URL : https://stackoverflow.com/questions/1883421/removing-array-item-by-value

반응형