복붙노트

조건으로 배열을 필터링하는 방법

PHP

조건으로 배열을 필터링하는 방법

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

array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2)

이제는 어떤 조건으로 그 배열을 필터링하고 값이 2 인 요소 만 유지하고 값이 2가 아닌 모든 요소를 ​​삭제하려고합니다.

그래서 내 기대 결과 배열은 다음과 같습니다.

array("a" => 2, "c" => 2, "f" => 2)

참고 : 원래 배열에서 키를 유지하려고합니다.

PHP로 어떻게 할 수 있습니까? 내장 함수가 있습니까?

해결법

  1. ==============================

    1.

    $fullarray = array('a'=>2,'b'=>4,'c'=>2,'d'=>5,'e'=>6,'f'=>2);
    
    
    function filterArray($value){
        return ($value == 2);
    }
    
    $filteredArray = array_filter($fullArray, 'filterArray');
    
    foreach($filteredArray as $k => $v){
        echo "$k = $v";
    }
    
  2. ==============================

    2.당신은 어떻게 든 당신의 배열을 통해 반복하고 각 요소를 당신의 조건으로 필터링해야합니다. 이것은 다양한 방법으로 수행 할 수 있습니다.

    당신은 어떻게 든 당신의 배열을 통해 반복하고 각 요소를 당신의 조건으로 필터링해야합니다. 이것은 다양한 방법으로 수행 할 수 있습니다.

    원하는 루프로 배열을 반복 할 수 있습니다. while, for 또는 foreach 일 수 있습니다. 그런 다음 조건을 확인하고 조건을 충족시키지 못하면 요소의 설정을 해제 (unset)하거나 조건에 맞는 요소를 새로운 배열로 작성하십시오.

    //while loop
    while(list($key, $value) = each($array)){
        //condition
    }
    
    //for loop
    $keys = array_keys($array);
    for($counter = 0, $length = count($array); $counter < $length; $counter++){
        $key = $keys[$counter];
        $value = $array[$key];
        //condition 
    }
    
    //foreach loop
    foreach($array as $key => $value){
        //condition
    }
    

    comment // 조건이있는 루프에 조건을 넣으십시오. 조건은 원하는 것을 검사 할 수 있습니다. 그런 다음 조건에 맞지 않는 요소를 해제 (unset)하거나 원하는 경우 array_values ​​()로 배열을 다시 색인 할 수 있습니다. 조건.

    //Pseudo code
    //Use one of the two ways
    if(condition){  //1. Condition fulfilled
        $newArray[ ] = $value;
                //↑ Put '$key' there, if you want to keep the original keys
                //Result array is: $newArray
    
    } else {        //2. Condition NOT fulfilled
        unset($array[$key]);
        //Use array_values() after the loop if you want to reindex the array
        //Result array is: $array
    }
    
    

    또 다른 방법은 array_filter () 내장 함수를 사용하는 것입니다. 일반적으로 간단한 루프를 사용하는 메서드와 거의 동일하게 작동합니다.

    요소를 배열에 보관하려면 TRUE를 반환하고 결과 배열에서 요소를 삭제하려면 FALSE 만 반환하면됩니다.

    //Anonymous function
    $newArray = array_filter($array, function($value, $key){
        //condition
    }, ARRAY_FILTER_USE_BOTH);
    
    //Function name passed as string
    function filter($value, $key){
        //condition
    }
    $newArray = array_filter($array, "filter", ARRAY_FILTER_USE_BOTH);
    
    //'create_function()', NOT recommended
    $newArray = array_filter($array, create_function('$value, $key', '/* condition */'), ARRAY_FILTER_USE_BOTH);
    

    preg_grep ()은 배열을 필터링하기 위해 정규식만을 사용한다는 점에서 array_filter ()와 유사합니다. 따라서 정규식을 필터로만 사용할 수 있고 값으로 필터링하거나 키로 더 많은 코드로 필터링 할 수 있기 때문에 모든 작업을 수행하지 못할 수도 있습니다.

    또한 결과를 반전시키기 위해 PREG_GREP_INVERT 플래그를 세 번째 매개 변수로 전달할 수 있습니다.

    //Filter by values
    $newArray = preg_grep("/regex/", $array);
    

    배열을 필터링하는 데 사용되는 공통 조건은 많이 있으며 배열의 값 또는 키에 모두 적용 할 수 있습니다. 여기에 그 중 몇 가지를 열거합니다.

    //Odd values
    return $value & 1;
    
    //Even values
    return !($value & 1);
    
    //NOT null values
    return !is_null($value);
    
    //NOT 0 values
    return $value !== 0;
    
    //Contain certain value values
    return strpos($value, $needle) !== FALSE;  //Use 'use($needle)' to get the var into scope
    
    //Contain certain substring at position values
    return substr($value, $position, $length) === $subString;
    
    //NOT 'empty'(link) values
    array_filter($array);  //Leave out the callback parameter
    
  3. ==============================

    3.루프에서 unset ()을 사용할 수 있도록 키 복사본을 반복 할 수 있습니다.

    루프에서 unset ()을 사용할 수 있도록 키 복사본을 반복 할 수 있습니다.

    foreach (array_keys($array) as $key) {
        if ($array[$key] != 2)  {
            unset($array[$key]);
        }
    }
    

    이 방법의 장점은 배열에 큰 값이 포함되어있는 경우 메모리 효율성입니다. 중복되지 않습니다.

    편집 그냥 당신이 실제로 2의 값을 가진 키가 필요합니다 (당신은 이미 값을 알고) 나타났습니다 :

    $keys = array();
    foreach ($array as $key => $value) {
        if ($value == 2)  {
            $keys[] = $key;
        }
    }
    
  4. ==============================

    4.이 작업은 가능하지만 많은 데이터를 복사 할 가능성이 높기 때문에 얼마나 효율적인지 확신 할 수 없습니다.

    이 작업은 가능하지만 많은 데이터를 복사 할 가능성이 높기 때문에 얼마나 효율적인지 확신 할 수 없습니다.

    $newArray = array_intersect_key(
                      $fullarray, 
                      array_flip(array_keys($fullarray, 2))
                );
    
  5. ==============================

    5.나는 다음과 같이 할 수있다.

    나는 다음과 같이 할 수있다.

    $newarray = array();
    foreach ($jsonarray as $testelement){
        if ($testelement == 2){$newarray[]=$testelement}
    }
    $result = count($newarray);
    
  6. ==============================

    6.

      foreach ($aray as $key => $value) {
        if (2 != $value) {
          unset($array($key));
        }
      }
    
      echo 'Items in array:' . count($array);
    
  7. ==============================

    7.나는 snappiest, readable built-in 함수가 다음과 같다고 생각한다. array_intersect ()

    나는 snappiest, readable built-in 함수가 다음과 같다고 생각한다. array_intersect ()

    이에 : (하지만)

    $array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
    var_export(array_intersect($array, [2]));
    

    산출:

    array (
      'a' => 2,
      'c' => 2,
      'f' => 2,
    )
    

    두 번째 매개 변수가 예상되는 값 유형이므로 배열로 선언해야합니다.

    이제 foreach 루프를 작성하거나 array_filter ()를 사용하여 문제가 발생하지 않으며보다 자세한 구문을 사용합니다.

    array_intersect ()는 두 번째 매개 변수 배열에 값을 더 추가하여 확장하기가 쉽습니다 (추가 "한정"값 포함).

  8. from https://stackoverflow.com/questions/1503579/how-to-filter-an-array-by-a-condition by cc-by-sa and MIT license