2012-09-02 11 views
0

다차원 배열의 하위 배열에있는 특정 요소가 값과 같지 않은지 확인하고 다중 배열의 해당 값으로 배열을 설정 해제합니다. 나는 쉽게 구현할 수 있도록 함수를 만들었지 만 작동하지 않는 것 같습니다. 그것의 값과 멀티 어레이로부터 어레이 미 설정 "-"각 서브 어레이가있는 경우이 경우 다차원 배열의 특정 값으로 배열 설정 해제 하시겠습니까?

function multi_unset($array, $unset) { 
    foreach($array as $key=>$value) { 
     $arrayU = $array[$key]; 
     $check = array(); 
     for($i = 0; $i < count($unset); $i++) { // produces $array[$key][0, 2, 3] 
      array_push($check, $arrayU[$unset[$i]]); 
     } 
     if(in_array("-", $check)) { 
      unset($array[$key]); 
     } 
    } 
    return $array; 
} 
$arr = array(array("-", "test", "test", "test"), array("test", "test", "test", "test")); 
$unset = array(0, 2, 3); // keys in individual arrays to check 
multi_unset($arr, $unset); 
print_r($arr); // Should output without $arr[0] 

는, I는 검사하고있다. 하위 배열 (0, 2, 3)의 특정 키만 검사하지만 변경하지 않고 배열을 출력합니다. 나는 어떤 범위를 잘못 잡아야한다는 것을 알았고 가능하면 "글로벌"을 사용하려했지만, 그것을 수정하지는 않았다.

+1

그래서'multi_unset ($ arr, $ unset);'은 $ arr에 실제로 아무것도하지 않습니다. 'multi_unset (& $ arr, $ unset);을 사용하여 리절 스하거나, 반환 값'$ arr = multi_unset ($ arr, $ unset);'을 사용하십시오. – ccKep

+0

내 이전 코멘트에 추가하려면 : call-time refrence by refrence는 실제로 PHP 5.3.0에서 사용되지 않으며 5.4.0에서 제거되었습니다. – ccKep

답변

0

는 버전을 약간 수정하고 반환 값을 처리.

function multi_unset($array, $unset) 
{ 
    $retVal = array(); 
    foreach($array as $key => $value) 
    { 
     $remove = false; 
     foreach($unset as $checkKey) 
     { 
      if ($value[$checkKey] == "-") 
       $remove = true; 
     } 
     if (!$remove) 
      $retVal[] = $value; 
    } 
    return $retVal; 
} 

$arr = array(array("-", "test", "test", "test"), array("test", "test", "test", "test")); 
$unset = array(0, 2, 3); 
$arr = multi_unset($arr, $unset); 
print_r($arr); 
+0

감사합니다. –

+0

코드를 연구 한 후에 기본적으로 "-"와 같지 않은 요소의 새로운 배열을 만듭니다. 그 맞습니까? 그리고 그들은 함수에서 배열을 변경할 수 없게되었습니다. 그리고 $ arr = multi_unset ($ arr, $ unset); 그 범주에 속할 것인가? –

+0

코드가 btw 감사했습니다 :) –

0

PHP에서 Passing by Reference와 PHP passing by 값을 비교할 수 있습니다. 세트 주어진 데이터와 함께 작동 Heres는 몇 가지 코드 ....

// Note the pass by reference. 
function multi_unset(&$array, $unset) { 
    foreach($array as $pos => $subArray) { 
     foreach($unset as $index) { 
      $found = ("-" == $subArray[$index]); 
      if($found){ 
       unset($subArray[$index]); 
          // Ver 2: remove sub array from main array; comment out previous line, and uncomment next line. 
          // unset($array[$pos]); 
      } 
      $array[$pos] = $subArray; // Ver 2: Comment this line out 
     } 
    } 
    //return $array; // No need to return since the array will be changed since we accepted a reference to it. 
} 
$arr = array(array("-", "test", "test", "test"), array("test", "test", "test", "test")); 
$unset = array(0, 2, 3); 
multi_unset($arr, $unset); 
print_r($arr); 
+0

그는 실제로 하위 배열에서 하나의 키 - 값 쌍만이 아니라 배열에서 전체 하위 배열을 제거하려고한다고 생각합니다. 그래도 틀릴 수도 있습니다. – ccKep

+0

좋은 전화 ccKep! 이 경우 : if ($ found) {unset ($ array [$ pos]);}'를 호출하고 if 뒤에 줄을 주석 처리합니다. – blad

관련 문제