dongpao5658 2015-04-13 08:31
浏览 22
已采纳

如何在PHP中的foreach循环中键入转换变量?

I'm looping through an array using a foreach loop:

$attributes = array( 'drink', 'price', 'amount' );

foreach ( $attributes as $key ) {
    $info[$key] = $key;
}

How can I type cast my $key variable differently each time the loop runs? For example, I need drink to be type string, price to be float and amount to be int.

Please note, this is a simplified example of my code. Type casting the keys before the loop is run isn't suitable in my case.

I tried the following but it didn't seem to work:

$attributes = array( 'drink' => 'string', 'price' => 'float', 'amount' => 'int' );

foreach ( $attributes as $key => $value ) {
    $info[$key] = ($value) $key;
}
  • 写回答

4条回答 默认 最新

  • douzi1986 2015-04-13 08:37
    关注

    This should work for you:

    (Here I use the key to then call either strval(), floatval() or intval())

    $attributes = array("str" => 'drink',"float"=> "10.5","int"=> "10" );
    foreach ( $attributes as $k => $key ) {
        $k.="val";
        $info[$key] = $k($key);
    }
    
    var_dump($info);
    

    output:

    array(3) {
      ["drink"]=>
      string(5) "drink"
      ["10.5"]=>
      float(10.5)
      [10]=>
      int(10)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?