2011-10-07 136 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; 
} 

(和抱歉,没有,你的方法并没有多大意义;-))