2010-12-10 71 views
3

我在PHP的foreach - 通过对象循环和改变值 - 的php5

简单凌晨冲洗功能这需要值的值或阵列和做一些输入清洗。现在,我使用的mysqli被取为对象,所以我需要能够将其应用到obejcts以及阵列行

function filter_out($output=''){ 
    if($output != ''){ 
     // i.e passed $_POST array 
     if(is_array($output)){ 
      $newoutput = array(); 
      foreach($output as $outputname=>$outputval){ 
       $newoutput[$outputname] = stripslashes($outputval); 
       $newoutput[$outputname] = htmlspecialchars($newoutput[$outputname]); 
      } 
     } else if(is_object($input)){ 
      ? 
     } 
    } 
} 

谁能告诉我怎么可以和对象作为输入做相同呢?

回答

3

你要找的功能是get_object_vars

$vars = get_object_vars($input); 
foreach ($vars as $outputname => $outputval) { 
    ///... 
} 

不要试图遍历对象本身(foreach ($object as $key => $value))上,因为它不会永远工作的权利。有时它会(stdClass为例),有时它不会(任何类实现Traversable ...

编辑

至于您的评论去......只要类AREN “T做什么好笑(__get__setprotectedprivate),你可以这样做:

$newoutput = clone $input; //make a copy to return 
$vars = get_object_vars($input); 
foreach ($vars as $outputname => $outputval) { 
    $newoutput->$outputname = htmlspecialchars(stripslashes($outputval)); 
} 

但我真的不能相信任何方法,将工作时间的100%......其他的选项,将会返回一个Nieve酒店的对象(stdclass),而不是提交一个:

$newoutput = new StdClass(); 
$vars = get_object_vars($input); 
foreach ($vars as $outputname => $outputval) { 
    $newoutput->$outputname = htmlspecialchars(stripslashes($outputval)); 
} 
+0

我不知道:“有时候它赢了(任何实现Traversable的类...“,你是不是指任何类**不实现Traversable?除非你的意思是”工作正确“意味着获得所有公共属性(而不是定制行为)? – netcoder 2010-12-10 18:14:31

+0

@netcoder:不,** a ny类实施... **是正确的。一个实现了'Traversable'的类将改变迭代行为,并且将会在迭代中返回对象属性。 – 2010-12-10 18:18:33

+0

@Stefan:嘿,这一切都取决于你对“工作权利”的定义。 ;-)但我明白了。 – netcoder 2010-12-10 18:19:25

0

要回答OP的评论ircmaxell's answer

$vars = get_object_vars($input); 
foreach ($vars as $outputname => $outputval) { 
    $input->$outputname = htmlspecialchars(stripslashes($outputval)); 
} 
0

既然你提到数组和对象从mysqli的我猜他们”来了重新只是stdClass,为什么不把这个对象转换成数组?

$newoutput = array() 
foreach ((array) $output as $key => $value) { 
    $newoutput[$key] = htmlspecialchars(stripslashes($value)); 
} 

或者你很可能只是做它在的地方:

$output = (array) $output; 
foreach ($output as &$value) { 
    $value = htmlspecialchars(stripslashes($value)); 
} 

所以单流可能看起来像:

function filter_out($output=''){ 
    if($output != ''){ 
    // i.e passed $_POST array 
    $is_array = is_array($output); 
    $output = (array) $output; 
    foreach($output as &$outputval){ 
     $outputval = htmlspecialchars(stripslashes($outputval)); 
    } 
    if (!$is_array) { 
     $output = (object) $output; 
    } 
    } 
    return $output; 
}