2011-10-07 149 views
0

我有一個簡單的函數:php函數並將兩個循環更改爲一個循環?

function test(){ 

    //some code 

    $X_has_val = $Y_has_val= array(); 

    foreach ($A as $id => $row){ 
     if(is_take($id)){ 
      $X_has_val[$id] = $row; 
     } 
    } 

    foreach ($B as $id => $row){ 
     if(is_take($id)){ 
      $Y_has_val[$id] = $row; 
     } 
    } 
    //some code 
} 

我這樣做是爲了獲得等價

function test(){ 
    //some code 
    $X_has_val = $Y_has_val= array(); 
    foreach(array($A, $B) as $key=>$value){ 
     foreach ($value as $id => $row){ 
      if(is_take($id)){ 
       $X_has_val[$id] = $row; 
       continue; 
       $Y_has_val[$id] = $row; 
      } 
     } 
    } 
    //some code 
} 

回答

2

看起來像所有你需要的是array_filter()

$X_has_cc = array_filter($A, 'isTake'); 
$Y_has_cc = array_filter($B, 'isTake'); 

例如像在

<?php 
test(); 

function test() { 
    $A = array(1,2,3,4,5,6,7,8,9,10); 
    $B = array(99,100,101,102,103,104); 

    $X_has_cc = array_filter($A, 'isTake'); 
    $Y_has_cc = array_filter($B, 'isTake'); 

    var_dump($X_has_cc, $Y_has_cc); 
} 

// select "even elements" 
function isTake($x) { 
    return 0==$x%2; 
} 

(和抱歉,沒有,你的方法並沒有多大意義;-))