开发者

how to cycle through array with multiple values

I know this question is simple, but I have little experience with arrays and am having difficulty. Anyway I have this array:

$variables=array("$value1" => "int",$value2 => "var",$value3 => "int");

I want to cycle through it and for ea开发者_如何学Pythonch $value I would like to add

$stmt->bindValue(1,$value, PDO::PARAM_INT); if $value is 'int' or

$stmt->bindValue(1,$value); if $value is 'var'

and have the '1' increase as it cycles through the variables. Does anyone know how to do this?


Maybe something like this:

$count = 1;
foreach ($variables as $key => $value){

  switch ($value) {
        case "int":
            $stmt->bindValue($count, $value, PDO::PARAM_INT); 
          break; 

        case "var":            
            $stmt->bindValue($count, $value);      
         break;

        default:
           exit("Invalid value");            

    }                
          $count++; 

}


A foreach loop lets you loop through your array. The foreach ($array as $k=>$v) syntax lets you define a variable to hold the current key ($k) and one for the current value ($v). I also used a simple variable that is incremented in every cycle ($i).

Then a simple if-elseif combo is used to do something different.

$i=1;
foreach ($variables as $k=>$v) {
    if ($v=='int') {
        $stmt->bindValue($i, $k, PDO::PARAM_INT);
    }
    elseif ($v=='var') {
        $stmt->bindValue($i, $k);
    }
    $i++;
}

This can be optimized further, I wanted to show the logic.


Simple loop should do it

$x=0;
foreach($variables as $key=>$value)
{
  if($value=="var")
   {
     $stmt->bindValue($x,$key);
   }
   else
   { 
      $stmt->bindValue($x,$value, PDO::PARAM_INT);
   }
  $x++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜